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.

391 lines
12 KiB

9 years ago
  1. package consensus
  2. import (
  3. "bytes"
  4. "fmt"
  5. "sort"
  6. "sync"
  7. "testing"
  8. "time"
  9. cfg "github.com/tendermint/go-config"
  10. dbm "github.com/tendermint/go-db"
  11. "github.com/tendermint/go-events"
  12. bc "github.com/tendermint/tendermint/blockchain"
  13. mempl "github.com/tendermint/tendermint/mempool"
  14. sm "github.com/tendermint/tendermint/state"
  15. "github.com/tendermint/tendermint/types"
  16. tmspcli "github.com/tendermint/tmsp/client"
  17. tmsp "github.com/tendermint/tmsp/types"
  18. "github.com/tendermint/tmsp/example/counter"
  19. )
  20. var config cfg.Config // NOTE: must be reset for each _test.go file
  21. var ensureTimeout = time.Duration(2)
  22. type validatorStub struct {
  23. Height int
  24. Round int
  25. *types.PrivValidator
  26. }
  27. func NewValidatorStub(privValidator *types.PrivValidator) *validatorStub {
  28. return &validatorStub{
  29. PrivValidator: privValidator,
  30. }
  31. }
  32. func (vs *validatorStub) signVote(voteType byte, hash []byte, header types.PartSetHeader) (*types.Vote, error) {
  33. vote := &types.Vote{
  34. Height: vs.Height,
  35. Round: vs.Round,
  36. Type: voteType,
  37. BlockHash: hash,
  38. BlockPartsHeader: header,
  39. }
  40. err := vs.PrivValidator.SignVote(config.GetString("chain_id"), vote)
  41. return vote, err
  42. }
  43. // convenienve function for testing
  44. func signVote(vs *validatorStub, voteType byte, hash []byte, header types.PartSetHeader) *types.Vote {
  45. v, err := vs.signVote(voteType, hash, header)
  46. if err != nil {
  47. panic(fmt.Errorf("failed to sign vote: %v", err))
  48. }
  49. return v
  50. }
  51. // create proposal block from cs1 but sign it with vs
  52. func decideProposal(cs1 *ConsensusState, cs2 *validatorStub, height, round int) (proposal *types.Proposal, block *types.Block) {
  53. block, blockParts := cs1.createProposalBlock()
  54. if block == nil { // on error
  55. panic("error creating proposal block")
  56. }
  57. // Make proposal
  58. proposal = types.NewProposal(height, round, blockParts.Header(), cs1.Votes.POLRound())
  59. if err := cs2.SignProposal(config.GetString("chain_id"), proposal); err != nil {
  60. panic(err)
  61. }
  62. return
  63. }
  64. //-------------------------------------------------------------------------------
  65. // utils
  66. /*
  67. func nilRound(t *testing.T, cs1 *ConsensusState, vss ...*validatorStub) {
  68. cs1.mtx.Lock()
  69. height, round := cs1.Height, cs1.Round
  70. cs1.mtx.Unlock()
  71. waitFor(t, cs1, height, round, RoundStepPrevote)
  72. signAddVoteToFromMany(types.VoteTypePrevote, cs1, nil, cs1.ProposalBlockParts.Header(), vss...)
  73. waitFor(t, cs1, height, round, RoundStepPrecommit)
  74. signAddVoteToFromMany(types.VoteTypePrecommit, cs1, nil, cs1.ProposalBlockParts.Header(), vss...)
  75. waitFor(t, cs1, height, round+1, RoundStepNewRound)
  76. }
  77. */
  78. // NOTE: this switches the propser as far as `perspectiveOf` is concerned,
  79. // but for simplicity we return a block it generated.
  80. func changeProposer(t *testing.T, perspectiveOf *ConsensusState, newProposer *validatorStub) *types.Block {
  81. _, v1 := perspectiveOf.Validators.GetByAddress(perspectiveOf.privValidator.Address)
  82. v1.Accum, v1.VotingPower = 0, 0
  83. if updated := perspectiveOf.Validators.Update(v1); !updated {
  84. t.Fatal("failed to update validator")
  85. }
  86. _, v2 := perspectiveOf.Validators.GetByAddress(newProposer.Address)
  87. v2.Accum, v2.VotingPower = 100, 100
  88. if updated := perspectiveOf.Validators.Update(v2); !updated {
  89. t.Fatal("failed to update validator")
  90. }
  91. // make the proposal
  92. propBlock, _ := perspectiveOf.createProposalBlock()
  93. if propBlock == nil {
  94. t.Fatal("Failed to create proposal block with cs2")
  95. }
  96. return propBlock
  97. }
  98. func fixVotingPower(t *testing.T, cs1 *ConsensusState, addr2 []byte) {
  99. _, v1 := cs1.Validators.GetByAddress(cs1.privValidator.Address)
  100. _, v2 := cs1.Validators.GetByAddress(addr2)
  101. v1.Accum, v1.VotingPower = v2.Accum, v2.VotingPower
  102. if updated := cs1.Validators.Update(v1); !updated {
  103. t.Fatal("failed to update validator")
  104. }
  105. }
  106. func addVoteToFromMany(to *ConsensusState, votes []*types.Vote, froms ...*validatorStub) {
  107. if len(votes) != len(froms) {
  108. panic("len(votes) and len(froms) must match")
  109. }
  110. for i, from := range froms {
  111. addVoteToFrom(to, from, votes[i])
  112. }
  113. }
  114. func addVoteToFrom(to *ConsensusState, from *validatorStub, vote *types.Vote) {
  115. valIndex, _ := to.Validators.GetByAddress(from.PrivValidator.Address)
  116. to.peerMsgQueue <- msgInfo{Msg: &VoteMessage{valIndex, vote}}
  117. // added, err := to.TryAddVote(valIndex, vote, "")
  118. /*
  119. if _, ok := err.(*types.ErrVoteConflictingSignature); ok {
  120. // let it fly
  121. } else if !added {
  122. fmt.Println("to, from, vote:", to.Height, from.Height, vote.Height)
  123. panic(fmt.Sprintln("Failed to add vote. Err:", err))
  124. } else if err != nil {
  125. panic(fmt.Sprintln("Failed to add vote:", err))
  126. }*/
  127. }
  128. func signVoteMany(voteType byte, hash []byte, header types.PartSetHeader, vss ...*validatorStub) []*types.Vote {
  129. votes := make([]*types.Vote, len(vss))
  130. for i, vs := range vss {
  131. votes[i] = signVote(vs, voteType, hash, header)
  132. }
  133. return votes
  134. }
  135. // add vote to one cs from another
  136. func signAddVoteToFromMany(voteType byte, to *ConsensusState, hash []byte, header types.PartSetHeader, froms ...*validatorStub) {
  137. for _, from := range froms {
  138. vote := signVote(from, voteType, hash, header)
  139. addVoteToFrom(to, from, vote)
  140. }
  141. }
  142. func signAddVoteToFrom(voteType byte, to *ConsensusState, from *validatorStub, hash []byte, header types.PartSetHeader) *types.Vote {
  143. vote := signVote(from, voteType, hash, header)
  144. addVoteToFrom(to, from, vote)
  145. return vote
  146. }
  147. func ensureNoNewStep(stepCh chan interface{}) {
  148. timeout := time.NewTicker(ensureTimeout * time.Second)
  149. select {
  150. case <-timeout.C:
  151. break
  152. case <-stepCh:
  153. panic("We should be stuck waiting for more votes, not moving to the next step")
  154. }
  155. }
  156. /*
  157. func ensureNoNewStep(t *testing.T, cs *ConsensusState) {
  158. timeout := time.NewTicker(ensureTimeout * time.Second)
  159. select {
  160. case <-timeout.C:
  161. break
  162. case <-cs.NewStepCh():
  163. panic("We should be stuck waiting for more votes, not moving to the next step")
  164. }
  165. }
  166. func ensureNewStep(t *testing.T, cs *ConsensusState) *RoundState {
  167. timeout := time.NewTicker(ensureTimeout * time.Second)
  168. select {
  169. case <-timeout.C:
  170. panic("We should have gone to the next step, not be stuck waiting")
  171. case rs := <-cs.NewStepCh():
  172. return rs
  173. }
  174. }
  175. func waitFor(t *testing.T, cs *ConsensusState, height int, round int, step RoundStepType) {
  176. for {
  177. rs := ensureNewStep(t, cs)
  178. if CompareHRS(rs.Height, rs.Round, rs.Step, height, round, step) < 0 {
  179. continue
  180. } else {
  181. break
  182. }
  183. }
  184. }
  185. */
  186. func incrementHeight(vss ...*validatorStub) {
  187. for _, vs := range vss {
  188. vs.Height += 1
  189. }
  190. }
  191. func incrementRound(vss ...*validatorStub) {
  192. for _, vs := range vss {
  193. vs.Round += 1
  194. }
  195. }
  196. func validatePrevote(t *testing.T, cs *ConsensusState, round int, privVal *validatorStub, blockHash []byte) {
  197. prevotes := cs.Votes.Prevotes(round)
  198. var vote *types.Vote
  199. if vote = prevotes.GetByAddress(privVal.Address); vote == nil {
  200. panic("Failed to find prevote from validator")
  201. }
  202. if blockHash == nil {
  203. if vote.BlockHash != nil {
  204. panic(fmt.Sprintf("Expected prevote to be for nil, got %X", vote.BlockHash))
  205. }
  206. } else {
  207. if !bytes.Equal(vote.BlockHash, blockHash) {
  208. panic(fmt.Sprintf("Expected prevote to be for %X, got %X", blockHash, vote.BlockHash))
  209. }
  210. }
  211. }
  212. func validateLastPrecommit(t *testing.T, cs *ConsensusState, privVal *validatorStub, blockHash []byte) {
  213. votes := cs.LastCommit
  214. var vote *types.Vote
  215. if vote = votes.GetByAddress(privVal.Address); vote == nil {
  216. panic("Failed to find precommit from validator")
  217. }
  218. if !bytes.Equal(vote.BlockHash, blockHash) {
  219. panic(fmt.Sprintf("Expected precommit to be for %X, got %X", blockHash, vote.BlockHash))
  220. }
  221. }
  222. func validatePrecommit(t *testing.T, cs *ConsensusState, thisRound, lockRound int, privVal *validatorStub, votedBlockHash, lockedBlockHash []byte) {
  223. precommits := cs.Votes.Precommits(thisRound)
  224. var vote *types.Vote
  225. if vote = precommits.GetByAddress(privVal.Address); vote == nil {
  226. panic("Failed to find precommit from validator")
  227. }
  228. if votedBlockHash == nil {
  229. if vote.BlockHash != nil {
  230. panic("Expected precommit to be for nil")
  231. }
  232. } else {
  233. if !bytes.Equal(vote.BlockHash, votedBlockHash) {
  234. panic("Expected precommit to be for proposal block")
  235. }
  236. }
  237. if lockedBlockHash == nil {
  238. if cs.LockedRound != lockRound || cs.LockedBlock != nil {
  239. panic(fmt.Sprintf("Expected to be locked on nil at round %d. Got locked at round %d with block %v", lockRound, cs.LockedRound, cs.LockedBlock))
  240. }
  241. } else {
  242. if cs.LockedRound != lockRound || !bytes.Equal(cs.LockedBlock.Hash(), lockedBlockHash) {
  243. panic(fmt.Sprintf("Expected block to be locked on round %d, got %d. Got locked block %X, expected %X", lockRound, cs.LockedRound, cs.LockedBlock.Hash(), lockedBlockHash))
  244. }
  245. }
  246. }
  247. func validatePrevoteAndPrecommit(t *testing.T, cs *ConsensusState, thisRound, lockRound int, privVal *validatorStub, votedBlockHash, lockedBlockHash []byte) {
  248. // verify the prevote
  249. validatePrevote(t, cs, thisRound, privVal, votedBlockHash)
  250. // verify precommit
  251. cs.mtx.Lock()
  252. validatePrecommit(t, cs, thisRound, lockRound, privVal, votedBlockHash, lockedBlockHash)
  253. cs.mtx.Unlock()
  254. }
  255. func fixedConsensusState() *ConsensusState {
  256. stateDB := dbm.NewMemDB()
  257. state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  258. privValidatorFile := config.GetString("priv_validator_file")
  259. privValidator := types.LoadOrGenPrivValidator(privValidatorFile)
  260. return newConsensusState(state, privValidator, counter.NewCounterApplication(true))
  261. }
  262. func newConsensusState(state *sm.State, pv *types.PrivValidator, app tmsp.Application) *ConsensusState {
  263. // Get BlockStore
  264. blockDB := dbm.NewMemDB()
  265. blockStore := bc.NewBlockStore(blockDB)
  266. // one for mempool, one for consensus
  267. mtx := new(sync.Mutex)
  268. proxyAppConnMem := tmspcli.NewLocalClient(mtx, app)
  269. proxyAppConnCon := tmspcli.NewLocalClient(mtx, app)
  270. // Make Mempool
  271. mempool := mempl.NewMempool(config, proxyAppConnMem)
  272. // Make ConsensusReactor
  273. cs := NewConsensusState(config, state, proxyAppConnCon, blockStore, mempool)
  274. cs.SetPrivValidator(pv)
  275. evsw := events.NewEventSwitch()
  276. cs.SetEventSwitch(evsw)
  277. evsw.Start()
  278. return cs
  279. }
  280. func randConsensusState(nValidators int) (*ConsensusState, []*validatorStub) {
  281. // Get State
  282. state, privVals := randGenesisState(nValidators, false, 10)
  283. vss := make([]*validatorStub, nValidators)
  284. cs := newConsensusState(state, privVals[0], counter.NewCounterApplication(true))
  285. for i := 0; i < nValidators; i++ {
  286. vss[i] = NewValidatorStub(privVals[i])
  287. }
  288. // since cs1 starts at 1
  289. incrementHeight(vss[1:]...)
  290. return cs, vss
  291. }
  292. func subscribeToVoter(cs *ConsensusState, addr []byte) chan interface{} {
  293. voteCh0 := subscribeToEvent(cs.evsw, "tester", types.EventStringVote(), 1)
  294. voteCh := make(chan interface{})
  295. go func() {
  296. for {
  297. v := <-voteCh0
  298. vote := v.(types.EventDataVote)
  299. // we only fire for our own votes
  300. if bytes.Equal(addr, vote.Address) {
  301. voteCh <- v
  302. }
  303. }
  304. }()
  305. return voteCh
  306. }
  307. func randGenesisState(numValidators int, randPower bool, minPower int64) (*sm.State, []*types.PrivValidator) {
  308. db := dbm.NewMemDB()
  309. genDoc, privValidators := randGenesisDoc(numValidators, randPower, minPower)
  310. s0 := sm.MakeGenesisState(db, genDoc)
  311. s0.Save()
  312. return s0, privValidators
  313. }
  314. func randGenesisDoc(numValidators int, randPower bool, minPower int64) (*types.GenesisDoc, []*types.PrivValidator) {
  315. validators := make([]types.GenesisValidator, numValidators)
  316. privValidators := make([]*types.PrivValidator, numValidators)
  317. for i := 0; i < numValidators; i++ {
  318. val, privVal := types.RandValidator(randPower, minPower)
  319. validators[i] = types.GenesisValidator{
  320. PubKey: val.PubKey,
  321. Amount: val.VotingPower,
  322. }
  323. privValidators[i] = privVal
  324. }
  325. sort.Sort(types.PrivValidatorsByAddress(privValidators))
  326. return &types.GenesisDoc{
  327. GenesisTime: time.Now(),
  328. ChainID: config.GetString("chain_id"),
  329. Validators: validators,
  330. }, privValidators
  331. }
  332. func startTestRound(cs *ConsensusState, height, round int) {
  333. cs.enterNewRound(height, round)
  334. cs.startRoutines(0)
  335. }