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.

735 lines
22 KiB

new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
7 years ago
7 years ago
8 years ago
  1. package consensus
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path"
  9. "reflect"
  10. "sort"
  11. "sync"
  12. "testing"
  13. "time"
  14. abcicli "github.com/tendermint/tendermint/abci/client"
  15. abci "github.com/tendermint/tendermint/abci/types"
  16. bc "github.com/tendermint/tendermint/blockchain"
  17. cfg "github.com/tendermint/tendermint/config"
  18. cstypes "github.com/tendermint/tendermint/consensus/types"
  19. cmn "github.com/tendermint/tendermint/libs/common"
  20. dbm "github.com/tendermint/tendermint/libs/db"
  21. "github.com/tendermint/tendermint/libs/log"
  22. mempl "github.com/tendermint/tendermint/mempool"
  23. "github.com/tendermint/tendermint/p2p"
  24. "github.com/tendermint/tendermint/privval"
  25. sm "github.com/tendermint/tendermint/state"
  26. "github.com/tendermint/tendermint/types"
  27. tmtime "github.com/tendermint/tendermint/types/time"
  28. "github.com/tendermint/tendermint/abci/example/counter"
  29. "github.com/tendermint/tendermint/abci/example/kvstore"
  30. "github.com/go-kit/kit/log/term"
  31. )
  32. const (
  33. testSubscriber = "test-client"
  34. )
  35. // genesis, chain_id, priv_val
  36. var config *cfg.Config // NOTE: must be reset for each _test.go file
  37. var ensureTimeout = time.Millisecond * 100
  38. func ensureDir(dir string, mode os.FileMode) {
  39. if err := cmn.EnsureDir(dir, mode); err != nil {
  40. panic(err)
  41. }
  42. }
  43. func ResetConfig(name string) *cfg.Config {
  44. return cfg.ResetTestRoot(name)
  45. }
  46. //-------------------------------------------------------------------------------
  47. // validator stub (a kvstore consensus peer we control)
  48. type validatorStub struct {
  49. Index int // Validator index. NOTE: we don't assume validator set changes.
  50. Height int64
  51. Round int
  52. types.PrivValidator
  53. }
  54. var testMinPower int64 = 10
  55. func NewValidatorStub(privValidator types.PrivValidator, valIndex int) *validatorStub {
  56. return &validatorStub{
  57. Index: valIndex,
  58. PrivValidator: privValidator,
  59. }
  60. }
  61. func (vs *validatorStub) signVote(voteType types.SignedMsgType, hash []byte, header types.PartSetHeader) (*types.Vote, error) {
  62. vote := &types.Vote{
  63. ValidatorIndex: vs.Index,
  64. ValidatorAddress: vs.PrivValidator.GetAddress(),
  65. Height: vs.Height,
  66. Round: vs.Round,
  67. Timestamp: tmtime.Now(),
  68. Type: voteType,
  69. BlockID: types.BlockID{hash, header},
  70. }
  71. err := vs.PrivValidator.SignVote(config.ChainID(), vote)
  72. return vote, err
  73. }
  74. // Sign vote for type/hash/header
  75. func signVote(vs *validatorStub, voteType types.SignedMsgType, hash []byte, header types.PartSetHeader) *types.Vote {
  76. v, err := vs.signVote(voteType, hash, header)
  77. if err != nil {
  78. panic(fmt.Errorf("failed to sign vote: %v", err))
  79. }
  80. return v
  81. }
  82. func signVotes(voteType types.SignedMsgType, hash []byte, header types.PartSetHeader, vss ...*validatorStub) []*types.Vote {
  83. votes := make([]*types.Vote, len(vss))
  84. for i, vs := range vss {
  85. votes[i] = signVote(vs, voteType, hash, header)
  86. }
  87. return votes
  88. }
  89. func incrementHeight(vss ...*validatorStub) {
  90. for _, vs := range vss {
  91. vs.Height++
  92. }
  93. }
  94. func incrementRound(vss ...*validatorStub) {
  95. for _, vs := range vss {
  96. vs.Round++
  97. }
  98. }
  99. //-------------------------------------------------------------------------------
  100. // Functions for transitioning the consensus state
  101. func startTestRound(cs *ConsensusState, height int64, round int) {
  102. cs.enterNewRound(height, round)
  103. cs.startRoutines(0)
  104. }
  105. // Create proposal block from cs1 but sign it with vs
  106. func decideProposal(cs1 *ConsensusState, vs *validatorStub, height int64, round int) (proposal *types.Proposal, block *types.Block) {
  107. block, blockParts := cs1.createProposalBlock()
  108. if block == nil { // on error
  109. panic("error creating proposal block")
  110. }
  111. // Make proposal
  112. polRound, propBlockID := cs1.ValidRound, types.BlockID{block.Hash(), blockParts.Header()}
  113. proposal = types.NewProposal(height, round, polRound, propBlockID)
  114. if err := vs.SignProposal(cs1.state.ChainID, proposal); err != nil {
  115. panic(err)
  116. }
  117. return
  118. }
  119. func addVotes(to *ConsensusState, votes ...*types.Vote) {
  120. for _, vote := range votes {
  121. to.peerMsgQueue <- msgInfo{Msg: &VoteMessage{vote}}
  122. }
  123. }
  124. func signAddVotes(to *ConsensusState, voteType types.SignedMsgType, hash []byte, header types.PartSetHeader, vss ...*validatorStub) {
  125. votes := signVotes(voteType, hash, header, vss...)
  126. addVotes(to, votes...)
  127. }
  128. func validatePrevote(t *testing.T, cs *ConsensusState, round int, privVal *validatorStub, blockHash []byte) {
  129. prevotes := cs.Votes.Prevotes(round)
  130. var vote *types.Vote
  131. if vote = prevotes.GetByAddress(privVal.GetAddress()); vote == nil {
  132. panic("Failed to find prevote from validator")
  133. }
  134. if blockHash == nil {
  135. if vote.BlockID.Hash != nil {
  136. panic(fmt.Sprintf("Expected prevote to be for nil, got %X", vote.BlockID.Hash))
  137. }
  138. } else {
  139. if !bytes.Equal(vote.BlockID.Hash, blockHash) {
  140. panic(fmt.Sprintf("Expected prevote to be for %X, got %X", blockHash, vote.BlockID.Hash))
  141. }
  142. }
  143. }
  144. func validateLastPrecommit(t *testing.T, cs *ConsensusState, privVal *validatorStub, blockHash []byte) {
  145. votes := cs.LastCommit
  146. var vote *types.Vote
  147. if vote = votes.GetByAddress(privVal.GetAddress()); vote == nil {
  148. panic("Failed to find precommit from validator")
  149. }
  150. if !bytes.Equal(vote.BlockID.Hash, blockHash) {
  151. panic(fmt.Sprintf("Expected precommit to be for %X, got %X", blockHash, vote.BlockID.Hash))
  152. }
  153. }
  154. func validatePrecommit(t *testing.T, cs *ConsensusState, thisRound, lockRound int, privVal *validatorStub, votedBlockHash, lockedBlockHash []byte) {
  155. precommits := cs.Votes.Precommits(thisRound)
  156. var vote *types.Vote
  157. if vote = precommits.GetByAddress(privVal.GetAddress()); vote == nil {
  158. panic("Failed to find precommit from validator")
  159. }
  160. if votedBlockHash == nil {
  161. if vote.BlockID.Hash != nil {
  162. panic("Expected precommit to be for nil")
  163. }
  164. } else {
  165. if !bytes.Equal(vote.BlockID.Hash, votedBlockHash) {
  166. panic("Expected precommit to be for proposal block")
  167. }
  168. }
  169. if lockedBlockHash == nil {
  170. if cs.LockedRound != lockRound || cs.LockedBlock != nil {
  171. 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))
  172. }
  173. } else {
  174. if cs.LockedRound != lockRound || !bytes.Equal(cs.LockedBlock.Hash(), lockedBlockHash) {
  175. 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))
  176. }
  177. }
  178. }
  179. func validatePrevoteAndPrecommit(t *testing.T, cs *ConsensusState, thisRound, lockRound int, privVal *validatorStub, votedBlockHash, lockedBlockHash []byte) {
  180. // verify the prevote
  181. validatePrevote(t, cs, thisRound, privVal, votedBlockHash)
  182. // verify precommit
  183. cs.mtx.Lock()
  184. validatePrecommit(t, cs, thisRound, lockRound, privVal, votedBlockHash, lockedBlockHash)
  185. cs.mtx.Unlock()
  186. }
  187. // genesis
  188. func subscribeToVoter(cs *ConsensusState, addr []byte) chan interface{} {
  189. voteCh0 := make(chan interface{})
  190. err := cs.eventBus.Subscribe(context.Background(), testSubscriber, types.EventQueryVote, voteCh0)
  191. if err != nil {
  192. panic(fmt.Sprintf("failed to subscribe %s to %v", testSubscriber, types.EventQueryVote))
  193. }
  194. voteCh := make(chan interface{})
  195. go func() {
  196. for v := range voteCh0 {
  197. vote := v.(types.EventDataVote)
  198. // we only fire for our own votes
  199. if bytes.Equal(addr, vote.Vote.ValidatorAddress) {
  200. voteCh <- v
  201. }
  202. }
  203. }()
  204. return voteCh
  205. }
  206. //-------------------------------------------------------------------------------
  207. // consensus states
  208. func newConsensusState(state sm.State, pv types.PrivValidator, app abci.Application) *ConsensusState {
  209. return newConsensusStateWithConfig(config, state, pv, app)
  210. }
  211. func newConsensusStateWithConfig(thisConfig *cfg.Config, state sm.State, pv types.PrivValidator, app abci.Application) *ConsensusState {
  212. blockDB := dbm.NewMemDB()
  213. return newConsensusStateWithConfigAndBlockStore(thisConfig, state, pv, app, blockDB)
  214. }
  215. func newConsensusStateWithConfigAndBlockStore(thisConfig *cfg.Config, state sm.State, pv types.PrivValidator, app abci.Application, blockDB dbm.DB) *ConsensusState {
  216. // Get BlockStore
  217. blockStore := bc.NewBlockStore(blockDB)
  218. // one for mempool, one for consensus
  219. mtx := new(sync.Mutex)
  220. proxyAppConnMem := abcicli.NewLocalClient(mtx, app)
  221. proxyAppConnCon := abcicli.NewLocalClient(mtx, app)
  222. // Make Mempool
  223. mempool := mempl.NewMempool(thisConfig.Mempool, proxyAppConnMem, 0)
  224. mempool.SetLogger(log.TestingLogger().With("module", "mempool"))
  225. if thisConfig.Consensus.WaitForTxs() {
  226. mempool.EnableTxsAvailable()
  227. }
  228. // mock the evidence pool
  229. evpool := sm.MockEvidencePool{}
  230. // Make ConsensusState
  231. stateDB := dbm.NewMemDB()
  232. blockExec := sm.NewBlockExecutor(stateDB, log.TestingLogger(), proxyAppConnCon, mempool, evpool)
  233. cs := NewConsensusState(thisConfig.Consensus, state, blockExec, blockStore, mempool, evpool)
  234. cs.SetLogger(log.TestingLogger().With("module", "consensus"))
  235. cs.SetPrivValidator(pv)
  236. eventBus := types.NewEventBus()
  237. eventBus.SetLogger(log.TestingLogger().With("module", "events"))
  238. eventBus.Start()
  239. cs.SetEventBus(eventBus)
  240. return cs
  241. }
  242. func loadPrivValidator(config *cfg.Config) *privval.FilePV {
  243. privValidatorFile := config.PrivValidatorFile()
  244. ensureDir(path.Dir(privValidatorFile), 0700)
  245. privValidator := privval.LoadOrGenFilePV(privValidatorFile)
  246. privValidator.Reset()
  247. return privValidator
  248. }
  249. func randConsensusState(nValidators int) (*ConsensusState, []*validatorStub) {
  250. // Get State
  251. state, privVals := randGenesisState(nValidators, false, 10)
  252. vss := make([]*validatorStub, nValidators)
  253. cs := newConsensusState(state, privVals[0], counter.NewCounterApplication(true))
  254. for i := 0; i < nValidators; i++ {
  255. vss[i] = NewValidatorStub(privVals[i], i)
  256. }
  257. // since cs1 starts at 1
  258. incrementHeight(vss[1:]...)
  259. return cs, vss
  260. }
  261. //-------------------------------------------------------------------------------
  262. func ensureNoNewEvent(ch <-chan interface{}, timeout time.Duration,
  263. errorMessage string) {
  264. select {
  265. case <-time.After(timeout):
  266. break
  267. case <-ch:
  268. panic(errorMessage)
  269. }
  270. }
  271. func ensureNoNewEventOnChannel(ch <-chan interface{}) {
  272. ensureNoNewEvent(
  273. ch,
  274. ensureTimeout,
  275. "We should be stuck waiting, not receiving new event on the channel")
  276. }
  277. func ensureNoNewRoundStep(stepCh <-chan interface{}) {
  278. ensureNoNewEvent(
  279. stepCh,
  280. ensureTimeout,
  281. "We should be stuck waiting, not receiving NewRoundStep event")
  282. }
  283. func ensureNoNewUnlock(unlockCh <-chan interface{}) {
  284. ensureNoNewEvent(
  285. unlockCh,
  286. ensureTimeout,
  287. "We should be stuck waiting, not receiving Unlock event")
  288. }
  289. func ensureNoNewTimeout(stepCh <-chan interface{}, timeout int64) {
  290. timeoutDuration := time.Duration(timeout*5) * time.Nanosecond
  291. ensureNoNewEvent(
  292. stepCh,
  293. timeoutDuration,
  294. "We should be stuck waiting, not receiving NewTimeout event")
  295. }
  296. func ensureNewEvent(
  297. ch <-chan interface{},
  298. height int64,
  299. round int,
  300. timeout time.Duration,
  301. errorMessage string) {
  302. select {
  303. case <-time.After(timeout):
  304. panic(errorMessage)
  305. case ev := <-ch:
  306. rs, ok := ev.(types.EventDataRoundState)
  307. if !ok {
  308. panic(
  309. fmt.Sprintf(
  310. "expected a EventDataRoundState, got %v.Wrong subscription channel?",
  311. reflect.TypeOf(rs)))
  312. }
  313. if rs.Height != height {
  314. panic(fmt.Sprintf("expected height %v, got %v", height, rs.Height))
  315. }
  316. if rs.Round != round {
  317. panic(fmt.Sprintf("expected round %v, got %v", round, rs.Round))
  318. }
  319. // TODO: We could check also for a step at this point!
  320. }
  321. }
  322. func ensureNewRoundStep(stepCh <-chan interface{}, height int64, round int) {
  323. ensureNewEvent(
  324. stepCh,
  325. height,
  326. round,
  327. ensureTimeout,
  328. "Timeout expired while waiting for NewStep event")
  329. }
  330. func ensureNewVote(voteCh <-chan interface{}, height int64, round int) {
  331. select {
  332. case <-time.After(ensureTimeout):
  333. break
  334. case v := <-voteCh:
  335. edv, ok := v.(types.EventDataVote)
  336. if !ok {
  337. panic(fmt.Sprintf("expected a *types.Vote, "+
  338. "got %v. wrong subscription channel?",
  339. reflect.TypeOf(v)))
  340. }
  341. vote := edv.Vote
  342. if vote.Height != height {
  343. panic(fmt.Sprintf("expected height %v, got %v", height, vote.Height))
  344. }
  345. if vote.Round != round {
  346. panic(fmt.Sprintf("expected round %v, got %v", round, vote.Round))
  347. }
  348. }
  349. }
  350. func ensureNewRound(roundCh <-chan interface{}, height int64, round int) {
  351. select {
  352. case <-time.After(ensureTimeout):
  353. panic("Timeout expired while waiting for NewRound event")
  354. case ev := <-roundCh:
  355. rs, ok := ev.(types.EventDataNewRound)
  356. if !ok {
  357. panic(
  358. fmt.Sprintf(
  359. "expected a EventDataNewRound, got %v.Wrong subscription channel?",
  360. reflect.TypeOf(rs)))
  361. }
  362. if rs.Height != height {
  363. panic(fmt.Sprintf("expected height %v, got %v", height, rs.Height))
  364. }
  365. if rs.Round != round {
  366. panic(fmt.Sprintf("expected round %v, got %v", round, rs.Round))
  367. }
  368. }
  369. }
  370. func ensureNewTimeout(timeoutCh <-chan interface{}, height int64, round int, timeout int64) {
  371. timeoutDuration := time.Duration(timeout*3) * time.Nanosecond
  372. ensureNewEvent(timeoutCh, height, round, timeoutDuration,
  373. "Timeout expired while waiting for NewTimeout event")
  374. }
  375. func ensureNewProposal(proposalCh <-chan interface{}, height int64, round int) {
  376. select {
  377. case <-time.After(ensureTimeout):
  378. panic("Timeout expired while waiting for NewProposal event")
  379. case ev := <-proposalCh:
  380. rs, ok := ev.(types.EventDataCompleteProposal)
  381. if !ok {
  382. panic(
  383. fmt.Sprintf(
  384. "expected a EventDataCompleteProposal, got %v.Wrong subscription channel?",
  385. reflect.TypeOf(rs)))
  386. }
  387. if rs.Height != height {
  388. panic(fmt.Sprintf("expected height %v, got %v", height, rs.Height))
  389. }
  390. if rs.Round != round {
  391. panic(fmt.Sprintf("expected round %v, got %v", round, rs.Round))
  392. }
  393. }
  394. }
  395. func ensureNewValidBlock(validBlockCh <-chan interface{}, height int64, round int) {
  396. ensureNewEvent(validBlockCh, height, round, ensureTimeout,
  397. "Timeout expired while waiting for NewValidBlock event")
  398. }
  399. func ensureNewBlock(blockCh <-chan interface{}, height int64) {
  400. select {
  401. case <-time.After(ensureTimeout):
  402. panic("Timeout expired while waiting for NewBlock event")
  403. case ev := <-blockCh:
  404. block, ok := ev.(types.EventDataNewBlock)
  405. if !ok {
  406. panic(fmt.Sprintf("expected a *types.EventDataNewBlock, "+
  407. "got %v. wrong subscription channel?",
  408. reflect.TypeOf(block)))
  409. }
  410. if block.Block.Height != height {
  411. panic(fmt.Sprintf("expected height %v, got %v", height, block.Block.Height))
  412. }
  413. }
  414. }
  415. func ensureNewBlockHeader(blockCh <-chan interface{}, height int64, blockHash cmn.HexBytes) {
  416. select {
  417. case <-time.After(ensureTimeout):
  418. panic("Timeout expired while waiting for NewBlockHeader event")
  419. case ev := <-blockCh:
  420. blockHeader, ok := ev.(types.EventDataNewBlockHeader)
  421. if !ok {
  422. panic(fmt.Sprintf("expected a *types.EventDataNewBlockHeader, "+
  423. "got %v. wrong subscription channel?",
  424. reflect.TypeOf(blockHeader)))
  425. }
  426. if blockHeader.Header.Height != height {
  427. panic(fmt.Sprintf("expected height %v, got %v", height, blockHeader.Header.Height))
  428. }
  429. if !bytes.Equal(blockHeader.Header.Hash(), blockHash) {
  430. panic(fmt.Sprintf("expected header %X, got %X", blockHash, blockHeader.Header.Hash()))
  431. }
  432. }
  433. }
  434. func ensureNewUnlock(unlockCh <-chan interface{}, height int64, round int) {
  435. ensureNewEvent(unlockCh, height, round, ensureTimeout,
  436. "Timeout expired while waiting for NewUnlock event")
  437. }
  438. func ensureVote(voteCh <-chan interface{}, height int64, round int,
  439. voteType types.SignedMsgType) {
  440. select {
  441. case <-time.After(ensureTimeout):
  442. panic("Timeout expired while waiting for NewVote event")
  443. case v := <-voteCh:
  444. edv, ok := v.(types.EventDataVote)
  445. if !ok {
  446. panic(fmt.Sprintf("expected a *types.Vote, "+
  447. "got %v. wrong subscription channel?",
  448. reflect.TypeOf(v)))
  449. }
  450. vote := edv.Vote
  451. if vote.Height != height {
  452. panic(fmt.Sprintf("expected height %v, got %v", height, vote.Height))
  453. }
  454. if vote.Round != round {
  455. panic(fmt.Sprintf("expected round %v, got %v", round, vote.Round))
  456. }
  457. if vote.Type != voteType {
  458. panic(fmt.Sprintf("expected type %v, got %v", voteType, vote.Type))
  459. }
  460. }
  461. }
  462. func ensureProposal(proposalCh <-chan interface{}, height int64, round int, propId types.BlockID) {
  463. select {
  464. case <-time.After(ensureTimeout):
  465. panic("Timeout expired while waiting for NewProposal event")
  466. case ev := <-proposalCh:
  467. rs, ok := ev.(types.EventDataCompleteProposal)
  468. if !ok {
  469. panic(
  470. fmt.Sprintf(
  471. "expected a EventDataCompleteProposal, got %v.Wrong subscription channel?",
  472. reflect.TypeOf(rs)))
  473. }
  474. if rs.Height != height {
  475. panic(fmt.Sprintf("expected height %v, got %v", height, rs.Height))
  476. }
  477. if rs.Round != round {
  478. panic(fmt.Sprintf("expected round %v, got %v", round, rs.Round))
  479. }
  480. if !rs.BlockID.Equals(propId) {
  481. panic("Proposed block does not match expected block")
  482. }
  483. }
  484. }
  485. func ensurePrecommit(voteCh <-chan interface{}, height int64, round int) {
  486. ensureVote(voteCh, height, round, types.PrecommitType)
  487. }
  488. func ensurePrevote(voteCh <-chan interface{}, height int64, round int) {
  489. ensureVote(voteCh, height, round, types.PrevoteType)
  490. }
  491. func ensureNewEventOnChannel(ch <-chan interface{}) {
  492. select {
  493. case <-time.After(ensureTimeout):
  494. panic("Timeout expired while waiting for new activity on the channel")
  495. case <-ch:
  496. }
  497. }
  498. //-------------------------------------------------------------------------------
  499. // consensus nets
  500. // consensusLogger is a TestingLogger which uses a different
  501. // color for each validator ("validator" key must exist).
  502. func consensusLogger() log.Logger {
  503. return log.TestingLoggerWithColorFn(func(keyvals ...interface{}) term.FgBgColor {
  504. for i := 0; i < len(keyvals)-1; i += 2 {
  505. if keyvals[i] == "validator" {
  506. return term.FgBgColor{Fg: term.Color(uint8(keyvals[i+1].(int) + 1))}
  507. }
  508. }
  509. return term.FgBgColor{}
  510. }).With("module", "consensus")
  511. }
  512. func randConsensusNet(nValidators int, testName string, tickerFunc func() TimeoutTicker, appFunc func() abci.Application, configOpts ...func(*cfg.Config)) []*ConsensusState {
  513. genDoc, privVals := randGenesisDoc(nValidators, false, 30)
  514. css := make([]*ConsensusState, nValidators)
  515. logger := consensusLogger()
  516. for i := 0; i < nValidators; i++ {
  517. stateDB := dbm.NewMemDB() // each state needs its own db
  518. state, _ := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  519. thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
  520. for _, opt := range configOpts {
  521. opt(thisConfig)
  522. }
  523. ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal
  524. app := appFunc()
  525. vals := types.TM2PB.ValidatorUpdates(state.Validators)
  526. app.InitChain(abci.RequestInitChain{Validators: vals})
  527. css[i] = newConsensusStateWithConfig(thisConfig, state, privVals[i], app)
  528. css[i].SetTimeoutTicker(tickerFunc())
  529. css[i].SetLogger(logger.With("validator", i, "module", "consensus"))
  530. }
  531. return css
  532. }
  533. // nPeers = nValidators + nNotValidator
  534. func randConsensusNetWithPeers(nValidators, nPeers int, testName string, tickerFunc func() TimeoutTicker, appFunc func() abci.Application) []*ConsensusState {
  535. genDoc, privVals := randGenesisDoc(nValidators, false, testMinPower)
  536. css := make([]*ConsensusState, nPeers)
  537. logger := consensusLogger()
  538. for i := 0; i < nPeers; i++ {
  539. stateDB := dbm.NewMemDB() // each state needs its own db
  540. state, _ := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  541. thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
  542. ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal
  543. var privVal types.PrivValidator
  544. if i < nValidators {
  545. privVal = privVals[i]
  546. } else {
  547. tempFile, err := ioutil.TempFile("", "priv_validator_")
  548. if err != nil {
  549. panic(err)
  550. }
  551. privVal = privval.GenFilePV(tempFile.Name())
  552. }
  553. app := appFunc()
  554. vals := types.TM2PB.ValidatorUpdates(state.Validators)
  555. app.InitChain(abci.RequestInitChain{Validators: vals})
  556. css[i] = newConsensusStateWithConfig(thisConfig, state, privVal, app)
  557. css[i].SetTimeoutTicker(tickerFunc())
  558. css[i].SetLogger(logger.With("validator", i, "module", "consensus"))
  559. }
  560. return css
  561. }
  562. func getSwitchIndex(switches []*p2p.Switch, peer p2p.Peer) int {
  563. for i, s := range switches {
  564. if peer.NodeInfo().ID() == s.NodeInfo().ID() {
  565. return i
  566. }
  567. }
  568. panic("didnt find peer in switches")
  569. return -1
  570. }
  571. //-------------------------------------------------------------------------------
  572. // genesis
  573. func randGenesisDoc(numValidators int, randPower bool, minPower int64) (*types.GenesisDoc, []types.PrivValidator) {
  574. validators := make([]types.GenesisValidator, numValidators)
  575. privValidators := make([]types.PrivValidator, numValidators)
  576. for i := 0; i < numValidators; i++ {
  577. val, privVal := types.RandValidator(randPower, minPower)
  578. validators[i] = types.GenesisValidator{
  579. PubKey: val.PubKey,
  580. Power: val.VotingPower,
  581. }
  582. privValidators[i] = privVal
  583. }
  584. sort.Sort(types.PrivValidatorsByAddress(privValidators))
  585. return &types.GenesisDoc{
  586. GenesisTime: tmtime.Now(),
  587. ChainID: config.ChainID(),
  588. Validators: validators,
  589. }, privValidators
  590. }
  591. func randGenesisState(numValidators int, randPower bool, minPower int64) (sm.State, []types.PrivValidator) {
  592. genDoc, privValidators := randGenesisDoc(numValidators, randPower, minPower)
  593. s0, _ := sm.MakeGenesisState(genDoc)
  594. return s0, privValidators
  595. }
  596. //------------------------------------
  597. // mock ticker
  598. func newMockTickerFunc(onlyOnce bool) func() TimeoutTicker {
  599. return func() TimeoutTicker {
  600. return &mockTicker{
  601. c: make(chan timeoutInfo, 10),
  602. onlyOnce: onlyOnce,
  603. }
  604. }
  605. }
  606. // mock ticker only fires on RoundStepNewHeight
  607. // and only once if onlyOnce=true
  608. type mockTicker struct {
  609. c chan timeoutInfo
  610. mtx sync.Mutex
  611. onlyOnce bool
  612. fired bool
  613. }
  614. func (m *mockTicker) Start() error {
  615. return nil
  616. }
  617. func (m *mockTicker) Stop() error {
  618. return nil
  619. }
  620. func (m *mockTicker) ScheduleTimeout(ti timeoutInfo) {
  621. m.mtx.Lock()
  622. defer m.mtx.Unlock()
  623. if m.onlyOnce && m.fired {
  624. return
  625. }
  626. if ti.Step == cstypes.RoundStepNewHeight {
  627. m.c <- ti
  628. m.fired = true
  629. }
  630. }
  631. func (m *mockTicker) Chan() <-chan timeoutInfo {
  632. return m.c
  633. }
  634. func (mockTicker) SetLogger(log.Logger) {
  635. }
  636. //------------------------------------
  637. func newCounter() abci.Application {
  638. return counter.NewCounterApplication(true)
  639. }
  640. func newPersistentKVStore() abci.Application {
  641. dir, _ := ioutil.TempDir("/tmp", "persistent-kvstore")
  642. return kvstore.NewPersistentKVStoreApplication(dir)
  643. }