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.

600 lines
18 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 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 types.PrivValidator) *types.PrivValidatorFS {
  145. return pv.(*types.PrivValidatorFS)
  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. )
  231. //---------------------------------------
  232. // Test handshake/replay
  233. // 0 - all synced up
  234. // 1 - saved block but app and state are behind
  235. // 2 - save block and committed but state is behind
  236. var modes = []uint{0, 1, 2}
  237. // Sync from scratch
  238. func TestHandshakeReplayAll(t *testing.T) {
  239. for _, m := range modes {
  240. testHandshakeReplay(t, 0, m)
  241. }
  242. }
  243. // Sync many, not from scratch
  244. func TestHandshakeReplaySome(t *testing.T) {
  245. for _, m := range modes {
  246. testHandshakeReplay(t, 1, m)
  247. }
  248. }
  249. // Sync from lagging by one
  250. func TestHandshakeReplayOne(t *testing.T) {
  251. for _, m := range modes {
  252. testHandshakeReplay(t, NUM_BLOCKS-1, m)
  253. }
  254. }
  255. // Sync from caught up
  256. func TestHandshakeReplayNone(t *testing.T) {
  257. for _, m := range modes {
  258. testHandshakeReplay(t, NUM_BLOCKS, m)
  259. }
  260. }
  261. // Make some blocks. Start a fresh app and apply nBlocks blocks. Then restart the app and sync it up with the remaining blocks
  262. func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) {
  263. config := ResetConfig("proxy_test_")
  264. // copy the many_blocks file
  265. walBody, err := cmn.ReadFile(path.Join(data_dir, "many_blocks.cswal"))
  266. if err != nil {
  267. t.Fatal(err)
  268. }
  269. walFile := writeWAL(string(walBody))
  270. config.Consensus.SetWalFile(walFile)
  271. privVal := types.LoadPrivValidatorFS(config.PrivValidatorFile())
  272. wal, err := NewWAL(walFile, false)
  273. if err != nil {
  274. t.Fatal(err)
  275. }
  276. wal.SetLogger(log.TestingLogger())
  277. if _, err := wal.Start(); err != nil {
  278. t.Fatal(err)
  279. }
  280. chain, commits, err := makeBlockchainFromWAL(wal)
  281. if err != nil {
  282. t.Fatalf(err.Error())
  283. }
  284. state, store := stateAndStore(config, privVal.GetPubKey())
  285. store.chain = chain
  286. store.commits = commits
  287. // run the chain through state.ApplyBlock to build up the tendermint state
  288. latestAppHash := buildTMStateFromChain(config, state, chain, mode)
  289. // make a new client creator
  290. dummyApp := dummy.NewPersistentDummyApplication(path.Join(config.DBDir(), "2"))
  291. clientCreator2 := proxy.NewLocalClientCreator(dummyApp)
  292. if nBlocks > 0 {
  293. // run nBlocks against a new client to build up the app state.
  294. // use a throwaway tendermint state
  295. proxyApp := proxy.NewAppConns(clientCreator2, nil)
  296. state, _ := stateAndStore(config, privVal.GetPubKey())
  297. buildAppStateFromChain(proxyApp, state, chain, nBlocks, mode)
  298. }
  299. // now start the app using the handshake - it should sync
  300. handshaker := NewHandshaker(state, store)
  301. proxyApp := proxy.NewAppConns(clientCreator2, handshaker)
  302. if _, err := proxyApp.Start(); err != nil {
  303. t.Fatalf("Error starting proxy app connections: %v", err)
  304. }
  305. // get the latest app hash from the app
  306. res, err := proxyApp.Query().InfoSync()
  307. if err != nil {
  308. t.Fatal(err)
  309. }
  310. // the app hash should be synced up
  311. if !bytes.Equal(latestAppHash, res.LastBlockAppHash) {
  312. t.Fatalf("Expected app hashes to match after handshake/replay. got %X, expected %X", res.LastBlockAppHash, latestAppHash)
  313. }
  314. expectedBlocksToSync := NUM_BLOCKS - nBlocks
  315. if nBlocks == NUM_BLOCKS && mode > 0 {
  316. expectedBlocksToSync += 1
  317. } else if nBlocks > 0 && mode == 1 {
  318. expectedBlocksToSync += 1
  319. }
  320. if handshaker.NBlocks() != expectedBlocksToSync {
  321. t.Fatalf("Expected handshake to sync %d blocks, got %d", expectedBlocksToSync, handshaker.NBlocks())
  322. }
  323. }
  324. func applyBlock(st *sm.State, blk *types.Block, proxyApp proxy.AppConns) {
  325. testPartSize := st.Params().BlockPartSizeBytes
  326. err := st.ApplyBlock(nil, proxyApp.Consensus(), blk, blk.MakePartSet(testPartSize).Header(), mempool)
  327. if err != nil {
  328. panic(err)
  329. }
  330. }
  331. func buildAppStateFromChain(proxyApp proxy.AppConns,
  332. state *sm.State, chain []*types.Block, nBlocks int, mode uint) {
  333. // start a new app without handshake, play nBlocks blocks
  334. if _, err := proxyApp.Start(); err != nil {
  335. panic(err)
  336. }
  337. validators := types.TM2PB.Validators(state.Validators)
  338. proxyApp.Consensus().InitChainSync(validators)
  339. defer proxyApp.Stop()
  340. switch mode {
  341. case 0:
  342. for i := 0; i < nBlocks; i++ {
  343. block := chain[i]
  344. applyBlock(state, block, proxyApp)
  345. }
  346. case 1, 2:
  347. for i := 0; i < nBlocks-1; i++ {
  348. block := chain[i]
  349. applyBlock(state, block, proxyApp)
  350. }
  351. if mode == 2 {
  352. // update the dummy height and apphash
  353. // as if we ran commit but not
  354. applyBlock(state, chain[nBlocks-1], proxyApp)
  355. }
  356. }
  357. }
  358. func buildTMStateFromChain(config *cfg.Config, state *sm.State, chain []*types.Block, mode uint) []byte {
  359. // run the whole chain against this client to build up the tendermint state
  360. clientCreator := proxy.NewLocalClientCreator(dummy.NewPersistentDummyApplication(path.Join(config.DBDir(), "1")))
  361. proxyApp := proxy.NewAppConns(clientCreator, nil) // sm.NewHandshaker(config, state, store, ReplayLastBlock))
  362. if _, err := proxyApp.Start(); err != nil {
  363. panic(err)
  364. }
  365. defer proxyApp.Stop()
  366. validators := types.TM2PB.Validators(state.Validators)
  367. proxyApp.Consensus().InitChainSync(validators)
  368. var latestAppHash []byte
  369. switch mode {
  370. case 0:
  371. // sync right up
  372. for _, block := range chain {
  373. applyBlock(state, block, proxyApp)
  374. }
  375. latestAppHash = state.AppHash
  376. case 1, 2:
  377. // sync up to the penultimate as if we stored the block.
  378. // whether we commit or not depends on the appHash
  379. for _, block := range chain[:len(chain)-1] {
  380. applyBlock(state, block, proxyApp)
  381. }
  382. // apply the final block to a state copy so we can
  383. // get the right next appHash but keep the state back
  384. stateCopy := state.Copy()
  385. applyBlock(stateCopy, chain[len(chain)-1], proxyApp)
  386. latestAppHash = stateCopy.AppHash
  387. }
  388. return latestAppHash
  389. }
  390. //--------------------------
  391. // utils for making blocks
  392. func makeBlockchainFromWAL(wal *WAL) ([]*types.Block, []*types.Commit, error) {
  393. // Search for height marker
  394. gr, found, err := wal.group.Search("#ENDHEIGHT: ", makeHeightSearchFunc(0))
  395. if err != nil {
  396. return nil, nil, err
  397. }
  398. if !found {
  399. return nil, nil, errors.New(cmn.Fmt("WAL does not contain height %d.", 1))
  400. }
  401. defer gr.Close()
  402. // log.Notice("Build a blockchain by reading from the WAL")
  403. var blockParts *types.PartSet
  404. var blocks []*types.Block
  405. var commits []*types.Commit
  406. for {
  407. line, err := gr.ReadLine()
  408. if err != nil {
  409. if err == io.EOF {
  410. break
  411. } else {
  412. return nil, nil, err
  413. }
  414. }
  415. piece, err := readPieceFromWAL([]byte(line))
  416. if err != nil {
  417. return nil, nil, err
  418. }
  419. if piece == nil {
  420. continue
  421. }
  422. switch p := piece.(type) {
  423. case *types.PartSetHeader:
  424. // if its not the first one, we have a full block
  425. if blockParts != nil {
  426. var n int
  427. block := wire.ReadBinary(&types.Block{}, blockParts.GetReader(), 0, &n, &err).(*types.Block)
  428. blocks = append(blocks, block)
  429. }
  430. blockParts = types.NewPartSetFromHeader(*p)
  431. case *types.Part:
  432. _, err := blockParts.AddPart(p, false)
  433. if err != nil {
  434. return nil, nil, err
  435. }
  436. case *types.Vote:
  437. if p.Type == types.VoteTypePrecommit {
  438. commit := &types.Commit{
  439. BlockID: p.BlockID,
  440. Precommits: []*types.Vote{p},
  441. }
  442. commits = append(commits, commit)
  443. }
  444. }
  445. }
  446. // grab the last block too
  447. var n int
  448. block := wire.ReadBinary(&types.Block{}, blockParts.GetReader(), 0, &n, &err).(*types.Block)
  449. blocks = append(blocks, block)
  450. return blocks, commits, nil
  451. }
  452. func readPieceFromWAL(msgBytes []byte) (interface{}, error) {
  453. // Skip over empty and meta lines
  454. if len(msgBytes) == 0 || msgBytes[0] == '#' {
  455. return nil, nil
  456. }
  457. var err error
  458. var msg TimedWALMessage
  459. wire.ReadJSON(&msg, msgBytes, &err)
  460. if err != nil {
  461. fmt.Println("MsgBytes:", msgBytes, string(msgBytes))
  462. return nil, fmt.Errorf("Error reading json data: %v", err)
  463. }
  464. // for logging
  465. switch m := msg.Msg.(type) {
  466. case msgInfo:
  467. switch msg := m.Msg.(type) {
  468. case *ProposalMessage:
  469. return &msg.Proposal.BlockPartsHeader, nil
  470. case *BlockPartMessage:
  471. return msg.Part, nil
  472. case *VoteMessage:
  473. return msg.Vote, nil
  474. }
  475. }
  476. return nil, nil
  477. }
  478. // fresh state and mock store
  479. func stateAndStore(config *cfg.Config, pubKey crypto.PubKey) (*sm.State, *mockBlockStore) {
  480. stateDB := dbm.NewMemDB()
  481. state, _ := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile())
  482. state.SetLogger(log.TestingLogger().With("module", "state"))
  483. store := NewMockBlockStore(config, state.Params())
  484. return state, store
  485. }
  486. //----------------------------------
  487. // mock block store
  488. type mockBlockStore struct {
  489. config *cfg.Config
  490. params types.ConsensusParams
  491. chain []*types.Block
  492. commits []*types.Commit
  493. }
  494. // TODO: NewBlockStore(db.NewMemDB) ...
  495. func NewMockBlockStore(config *cfg.Config, params types.ConsensusParams) *mockBlockStore {
  496. return &mockBlockStore{config, params, 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.params.BlockPartSizeBytes).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. }