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.

215 lines
6.5 KiB

9 years ago
  1. package consensus
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "path"
  7. "strings"
  8. "testing"
  9. "time"
  10. . "github.com/tendermint/go-common"
  11. "github.com/tendermint/go-wire"
  12. "github.com/tendermint/tendermint/types"
  13. )
  14. var data_dir = path.Join(GoPath, "src/github.com/tendermint/tendermint/consensus", "test_data")
  15. // the priv validator changes step at these lines for a block with 1 val and 1 part
  16. var baseStepChanges = []int{2, 5, 7}
  17. // test recovery from each line in each testCase
  18. var testCases = []*testCase{
  19. newTestCase("empty_block", baseStepChanges), // empty block (has 1 block part)
  20. newTestCase("small_block1", baseStepChanges), // small block with txs in 1 block part
  21. newTestCase("small_block2", []int{2, 7, 9}), // small block with txs across 3 smaller block parts
  22. }
  23. type testCase struct {
  24. name string
  25. log string //full cswal
  26. stepMap map[int]int8 // map lines of log to privval step
  27. proposeLine int
  28. prevoteLine int
  29. precommitLine int
  30. }
  31. func newTestCase(name string, stepChanges []int) *testCase {
  32. if len(stepChanges) != 3 {
  33. panic(Fmt("a full wal has 3 step changes! Got array %v", stepChanges))
  34. }
  35. return &testCase{
  36. name: name,
  37. log: readWAL(path.Join(data_dir, name+".cswal")),
  38. stepMap: newMapFromChanges(stepChanges),
  39. proposeLine: stepChanges[0],
  40. prevoteLine: stepChanges[1],
  41. precommitLine: stepChanges[2],
  42. }
  43. }
  44. func newMapFromChanges(changes []int) map[int]int8 {
  45. changes = append(changes, changes[2]+1) // so we add the last step change to the map
  46. m := make(map[int]int8)
  47. var count int
  48. for changeNum, nextChange := range changes {
  49. for ; count < nextChange; count++ {
  50. m[count] = int8(changeNum)
  51. }
  52. }
  53. return m
  54. }
  55. func readWAL(p string) string {
  56. b, err := ioutil.ReadFile(p)
  57. if err != nil {
  58. panic(err)
  59. }
  60. return string(b)
  61. }
  62. func writeWAL(log string) string {
  63. fmt.Println("writing", log)
  64. // write the needed wal to file
  65. f, err := ioutil.TempFile(os.TempDir(), "replay_test_")
  66. if err != nil {
  67. panic(err)
  68. }
  69. _, err = f.WriteString(log)
  70. if err != nil {
  71. panic(err)
  72. }
  73. name := f.Name()
  74. f.Close()
  75. return name
  76. }
  77. func waitForBlock(newBlockCh chan interface{}, thisCase *testCase, i int) {
  78. after := time.After(time.Second * 10)
  79. select {
  80. case <-newBlockCh:
  81. case <-after:
  82. panic(Fmt("Timed out waiting for new block for case '%s' line %d", thisCase.name, i))
  83. }
  84. }
  85. func runReplayTest(t *testing.T, cs *ConsensusState, fileName string, newBlockCh chan interface{},
  86. thisCase *testCase, i int) {
  87. cs.config.Set("cswal", fileName)
  88. cs.Start()
  89. // Wait to make a new block.
  90. // This is just a signal that we haven't halted; its not something contained in the WAL itself.
  91. // Assuming the consensus state is running, replay of any WAL, including the empty one,
  92. // should eventually be followed by a new block, or else something is wrong
  93. waitForBlock(newBlockCh, thisCase, i)
  94. cs.Stop()
  95. }
  96. func setupReplayTest(thisCase *testCase, nLines int, crashAfter bool) (*ConsensusState, chan interface{}, string, string) {
  97. fmt.Println("-------------------------------------")
  98. log.Notice(Fmt("Starting replay test of %d lines of WAL (crash before write)", nLines))
  99. lineStep := nLines
  100. if crashAfter {
  101. lineStep -= 1
  102. }
  103. split := strings.Split(thisCase.log, "\n")
  104. lastMsg := split[nLines]
  105. // we write those lines up to (not including) one with the signature
  106. fileName := writeWAL(strings.Join(split[:nLines], "\n") + "\n")
  107. cs := fixedConsensusStateDummy()
  108. // set the last step according to when we crashed vs the wal
  109. cs.privValidator.LastHeight = 1 // first block
  110. cs.privValidator.LastStep = thisCase.stepMap[lineStep]
  111. fmt.Println("LAST STEP", cs.privValidator.LastStep)
  112. newBlockCh := subscribeToEvent(cs.evsw, "tester", types.EventStringNewBlock(), 1)
  113. return cs, newBlockCh, lastMsg, fileName
  114. }
  115. //-----------------------------------------------
  116. // Test the log at every iteration, and set the privVal last step
  117. // as if the log was written after signing, before the crash
  118. func TestReplayCrashAfterWrite(t *testing.T) {
  119. for _, thisCase := range testCases {
  120. split := strings.Split(thisCase.log, "\n")
  121. for i := 0; i < len(split)-1; i++ {
  122. cs, newBlockCh, _, f := setupReplayTest(thisCase, i+1, true)
  123. runReplayTest(t, cs, f, newBlockCh, thisCase, i+1)
  124. }
  125. }
  126. }
  127. //-----------------------------------------------
  128. // Test the log as if we crashed after signing but before writing.
  129. // This relies on privValidator.LastSignature being set
  130. func TestReplayCrashBeforeWritePropose(t *testing.T) {
  131. for _, thisCase := range testCases {
  132. lineNum := thisCase.proposeLine
  133. cs, newBlockCh, proposalMsg, f := setupReplayTest(thisCase, lineNum, false) // propose
  134. // Set LastSig
  135. var err error
  136. var msg ConsensusLogMessage
  137. wire.ReadJSON(&msg, []byte(proposalMsg), &err)
  138. proposal := msg.Msg.(msgInfo).Msg.(*ProposalMessage)
  139. if err != nil {
  140. t.Fatalf("Error reading json data: %v", err)
  141. }
  142. cs.privValidator.LastSignBytes = types.SignBytes(cs.state.ChainID, proposal.Proposal)
  143. cs.privValidator.LastSignature = proposal.Proposal.Signature
  144. runReplayTest(t, cs, f, newBlockCh, thisCase, lineNum)
  145. }
  146. }
  147. func TestReplayCrashBeforeWritePrevote(t *testing.T) {
  148. for _, thisCase := range testCases {
  149. lineNum := thisCase.prevoteLine
  150. cs, newBlockCh, voteMsg, f := setupReplayTest(thisCase, lineNum, false) // prevote
  151. types.AddListenerForEvent(cs.evsw, "tester", types.EventStringCompleteProposal(), func(data types.TMEventData) {
  152. // Set LastSig
  153. var err error
  154. var msg ConsensusLogMessage
  155. wire.ReadJSON(&msg, []byte(voteMsg), &err)
  156. vote := msg.Msg.(msgInfo).Msg.(*VoteMessage)
  157. if err != nil {
  158. t.Fatalf("Error reading json data: %v", err)
  159. }
  160. cs.privValidator.LastSignBytes = types.SignBytes(cs.state.ChainID, vote.Vote)
  161. cs.privValidator.LastSignature = vote.Vote.Signature
  162. })
  163. runReplayTest(t, cs, f, newBlockCh, thisCase, lineNum)
  164. }
  165. }
  166. func TestReplayCrashBeforeWritePrecommit(t *testing.T) {
  167. for _, thisCase := range testCases {
  168. lineNum := thisCase.precommitLine
  169. cs, newBlockCh, voteMsg, f := setupReplayTest(thisCase, lineNum, false) // precommit
  170. types.AddListenerForEvent(cs.evsw, "tester", types.EventStringPolka(), func(data types.TMEventData) {
  171. // Set LastSig
  172. var err error
  173. var msg ConsensusLogMessage
  174. wire.ReadJSON(&msg, []byte(voteMsg), &err)
  175. vote := msg.Msg.(msgInfo).Msg.(*VoteMessage)
  176. if err != nil {
  177. t.Fatalf("Error reading json data: %v", err)
  178. }
  179. cs.privValidator.LastSignBytes = types.SignBytes(cs.state.ChainID, vote.Vote)
  180. cs.privValidator.LastSignature = vote.Vote.Signature
  181. })
  182. runReplayTest(t, cs, f, newBlockCh, thisCase, lineNum)
  183. }
  184. }