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.

397 lines
12 KiB

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