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.

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