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.

744 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
7 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
7 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
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
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
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
7 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
7 years ago
9 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
7 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/filepath"
  9. "reflect"
  10. "sort"
  11. "sync"
  12. "testing"
  13. "time"
  14. "github.com/go-kit/kit/log/term"
  15. abcicli "github.com/tendermint/tendermint/abci/client"
  16. "github.com/tendermint/tendermint/abci/example/counter"
  17. "github.com/tendermint/tendermint/abci/example/kvstore"
  18. abci "github.com/tendermint/tendermint/abci/types"
  19. bc "github.com/tendermint/tendermint/blockchain"
  20. cfg "github.com/tendermint/tendermint/config"
  21. cstypes "github.com/tendermint/tendermint/consensus/types"
  22. cmn "github.com/tendermint/tendermint/libs/common"
  23. dbm "github.com/tendermint/tendermint/libs/db"
  24. "github.com/tendermint/tendermint/libs/log"
  25. mempl "github.com/tendermint/tendermint/mempool"
  26. "github.com/tendermint/tendermint/p2p"
  27. "github.com/tendermint/tendermint/privval"
  28. sm "github.com/tendermint/tendermint/state"
  29. "github.com/tendermint/tendermint/types"
  30. tmtime "github.com/tendermint/tendermint/types/time"
  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. addr := vs.PrivValidator.GetPubKey().Address()
  63. vote := &types.Vote{
  64. ValidatorIndex: vs.Index,
  65. ValidatorAddress: addr,
  66. Height: vs.Height,
  67. Round: vs.Round,
  68. Timestamp: tmtime.Now(),
  69. Type: voteType,
  70. BlockID: types.BlockID{hash, header},
  71. }
  72. err := vs.PrivValidator.SignVote(config.ChainID(), vote)
  73. return vote, err
  74. }
  75. // Sign vote for type/hash/header
  76. func signVote(vs *validatorStub, voteType types.SignedMsgType, hash []byte, header types.PartSetHeader) *types.Vote {
  77. v, err := vs.signVote(voteType, hash, header)
  78. if err != nil {
  79. panic(fmt.Errorf("failed to sign vote: %v", err))
  80. }
  81. return v
  82. }
  83. func signVotes(voteType types.SignedMsgType, hash []byte, header types.PartSetHeader, vss ...*validatorStub) []*types.Vote {
  84. votes := make([]*types.Vote, len(vss))
  85. for i, vs := range vss {
  86. votes[i] = signVote(vs, voteType, hash, header)
  87. }
  88. return votes
  89. }
  90. func incrementHeight(vss ...*validatorStub) {
  91. for _, vs := range vss {
  92. vs.Height++
  93. }
  94. }
  95. func incrementRound(vss ...*validatorStub) {
  96. for _, vs := range vss {
  97. vs.Round++
  98. }
  99. }
  100. //-------------------------------------------------------------------------------
  101. // Functions for transitioning the consensus state
  102. func startTestRound(cs *ConsensusState, height int64, round int) {
  103. cs.enterNewRound(height, round)
  104. cs.startRoutines(0)
  105. }
  106. // Create proposal block from cs1 but sign it with vs
  107. func decideProposal(cs1 *ConsensusState, vs *validatorStub, height int64, round int) (proposal *types.Proposal, block *types.Block) {
  108. block, blockParts := cs1.createProposalBlock()
  109. if block == nil { // on error
  110. panic("error creating proposal block")
  111. }
  112. // Make proposal
  113. polRound, propBlockID := cs1.ValidRound, types.BlockID{block.Hash(), blockParts.Header()}
  114. proposal = types.NewProposal(height, round, polRound, propBlockID)
  115. if err := vs.SignProposal(cs1.state.ChainID, proposal); err != nil {
  116. panic(err)
  117. }
  118. return
  119. }
  120. func addVotes(to *ConsensusState, votes ...*types.Vote) {
  121. for _, vote := range votes {
  122. to.peerMsgQueue <- msgInfo{Msg: &VoteMessage{vote}}
  123. }
  124. }
  125. func signAddVotes(to *ConsensusState, voteType types.SignedMsgType, hash []byte, header types.PartSetHeader, vss ...*validatorStub) {
  126. votes := signVotes(voteType, hash, header, vss...)
  127. addVotes(to, votes...)
  128. }
  129. func validatePrevote(t *testing.T, cs *ConsensusState, round int, privVal *validatorStub, blockHash []byte) {
  130. prevotes := cs.Votes.Prevotes(round)
  131. address := privVal.GetPubKey().Address()
  132. var vote *types.Vote
  133. if vote = prevotes.GetByAddress(address); vote == nil {
  134. panic("Failed to find prevote from validator")
  135. }
  136. if blockHash == nil {
  137. if vote.BlockID.Hash != nil {
  138. panic(fmt.Sprintf("Expected prevote to be for nil, got %X", vote.BlockID.Hash))
  139. }
  140. } else {
  141. if !bytes.Equal(vote.BlockID.Hash, blockHash) {
  142. panic(fmt.Sprintf("Expected prevote to be for %X, got %X", blockHash, vote.BlockID.Hash))
  143. }
  144. }
  145. }
  146. func validateLastPrecommit(t *testing.T, cs *ConsensusState, privVal *validatorStub, blockHash []byte) {
  147. votes := cs.LastCommit
  148. address := privVal.GetPubKey().Address()
  149. var vote *types.Vote
  150. if vote = votes.GetByAddress(address); vote == nil {
  151. panic("Failed to find precommit from validator")
  152. }
  153. if !bytes.Equal(vote.BlockID.Hash, blockHash) {
  154. panic(fmt.Sprintf("Expected precommit to be for %X, got %X", blockHash, vote.BlockID.Hash))
  155. }
  156. }
  157. func validatePrecommit(t *testing.T, cs *ConsensusState, thisRound, lockRound int, privVal *validatorStub, votedBlockHash, lockedBlockHash []byte) {
  158. precommits := cs.Votes.Precommits(thisRound)
  159. address := privVal.GetPubKey().Address()
  160. var vote *types.Vote
  161. if vote = precommits.GetByAddress(address); vote == nil {
  162. panic("Failed to find precommit from validator")
  163. }
  164. if votedBlockHash == nil {
  165. if vote.BlockID.Hash != nil {
  166. panic("Expected precommit to be for nil")
  167. }
  168. } else {
  169. if !bytes.Equal(vote.BlockID.Hash, votedBlockHash) {
  170. panic("Expected precommit to be for proposal block")
  171. }
  172. }
  173. if lockedBlockHash == nil {
  174. if cs.LockedRound != lockRound || cs.LockedBlock != nil {
  175. 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))
  176. }
  177. } else {
  178. if cs.LockedRound != lockRound || !bytes.Equal(cs.LockedBlock.Hash(), lockedBlockHash) {
  179. 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))
  180. }
  181. }
  182. }
  183. func validatePrevoteAndPrecommit(t *testing.T, cs *ConsensusState, thisRound, lockRound int, privVal *validatorStub, votedBlockHash, lockedBlockHash []byte) {
  184. // verify the prevote
  185. validatePrevote(t, cs, thisRound, privVal, votedBlockHash)
  186. // verify precommit
  187. cs.mtx.Lock()
  188. validatePrecommit(t, cs, thisRound, lockRound, privVal, votedBlockHash, lockedBlockHash)
  189. cs.mtx.Unlock()
  190. }
  191. // genesis
  192. func subscribeToVoter(cs *ConsensusState, addr []byte) chan interface{} {
  193. voteCh0 := make(chan interface{})
  194. err := cs.eventBus.Subscribe(context.Background(), testSubscriber, types.EventQueryVote, voteCh0)
  195. if err != nil {
  196. panic(fmt.Sprintf("failed to subscribe %s to %v", testSubscriber, types.EventQueryVote))
  197. }
  198. voteCh := make(chan interface{})
  199. go func() {
  200. for v := range voteCh0 {
  201. vote := v.(types.EventDataVote)
  202. // we only fire for our own votes
  203. if bytes.Equal(addr, vote.Vote.ValidatorAddress) {
  204. voteCh <- v
  205. }
  206. }
  207. }()
  208. return voteCh
  209. }
  210. //-------------------------------------------------------------------------------
  211. // consensus states
  212. func newConsensusState(state sm.State, pv types.PrivValidator, app abci.Application) *ConsensusState {
  213. return newConsensusStateWithConfig(config, state, pv, app)
  214. }
  215. func newConsensusStateWithConfig(thisConfig *cfg.Config, state sm.State, pv types.PrivValidator, app abci.Application) *ConsensusState {
  216. blockDB := dbm.NewMemDB()
  217. return newConsensusStateWithConfigAndBlockStore(thisConfig, state, pv, app, blockDB)
  218. }
  219. func newConsensusStateWithConfigAndBlockStore(thisConfig *cfg.Config, state sm.State, pv types.PrivValidator, app abci.Application, blockDB dbm.DB) *ConsensusState {
  220. // Get BlockStore
  221. blockStore := bc.NewBlockStore(blockDB)
  222. // one for mempool, one for consensus
  223. mtx := new(sync.Mutex)
  224. proxyAppConnMem := abcicli.NewLocalClient(mtx, app)
  225. proxyAppConnCon := abcicli.NewLocalClient(mtx, app)
  226. // Make Mempool
  227. mempool := mempl.NewMempool(thisConfig.Mempool, proxyAppConnMem, 0)
  228. mempool.SetLogger(log.TestingLogger().With("module", "mempool"))
  229. if thisConfig.Consensus.WaitForTxs() {
  230. mempool.EnableTxsAvailable()
  231. }
  232. // mock the evidence pool
  233. evpool := sm.MockEvidencePool{}
  234. // Make ConsensusState
  235. stateDB := dbm.NewMemDB()
  236. blockExec := sm.NewBlockExecutor(stateDB, log.TestingLogger(), proxyAppConnCon, mempool, evpool)
  237. cs := NewConsensusState(thisConfig.Consensus, state, blockExec, blockStore, mempool, evpool)
  238. cs.SetLogger(log.TestingLogger().With("module", "consensus"))
  239. cs.SetPrivValidator(pv)
  240. eventBus := types.NewEventBus()
  241. eventBus.SetLogger(log.TestingLogger().With("module", "events"))
  242. eventBus.Start()
  243. cs.SetEventBus(eventBus)
  244. return cs
  245. }
  246. func loadPrivValidator(config *cfg.Config) *privval.FilePV {
  247. privValidatorKeyFile := config.PrivValidatorKeyFile()
  248. ensureDir(filepath.Dir(privValidatorKeyFile), 0700)
  249. privValidatorStateFile := config.PrivValidatorStateFile()
  250. privValidator := privval.LoadOrGenFilePV(privValidatorKeyFile, privValidatorStateFile)
  251. privValidator.Reset()
  252. return privValidator
  253. }
  254. func randConsensusState(nValidators int) (*ConsensusState, []*validatorStub) {
  255. // Get State
  256. state, privVals := randGenesisState(nValidators, false, 10)
  257. vss := make([]*validatorStub, nValidators)
  258. cs := newConsensusState(state, privVals[0], counter.NewCounterApplication(true))
  259. for i := 0; i < nValidators; i++ {
  260. vss[i] = NewValidatorStub(privVals[i], i)
  261. }
  262. // since cs1 starts at 1
  263. incrementHeight(vss[1:]...)
  264. return cs, vss
  265. }
  266. //-------------------------------------------------------------------------------
  267. func ensureNoNewEvent(ch <-chan interface{}, timeout time.Duration,
  268. errorMessage string) {
  269. select {
  270. case <-time.After(timeout):
  271. break
  272. case <-ch:
  273. panic(errorMessage)
  274. }
  275. }
  276. func ensureNoNewEventOnChannel(ch <-chan interface{}) {
  277. ensureNoNewEvent(
  278. ch,
  279. ensureTimeout,
  280. "We should be stuck waiting, not receiving new event on the channel")
  281. }
  282. func ensureNoNewRoundStep(stepCh <-chan interface{}) {
  283. ensureNoNewEvent(
  284. stepCh,
  285. ensureTimeout,
  286. "We should be stuck waiting, not receiving NewRoundStep event")
  287. }
  288. func ensureNoNewUnlock(unlockCh <-chan interface{}) {
  289. ensureNoNewEvent(
  290. unlockCh,
  291. ensureTimeout,
  292. "We should be stuck waiting, not receiving Unlock event")
  293. }
  294. func ensureNoNewTimeout(stepCh <-chan interface{}, timeout int64) {
  295. timeoutDuration := time.Duration(timeout*5) * time.Nanosecond
  296. ensureNoNewEvent(
  297. stepCh,
  298. timeoutDuration,
  299. "We should be stuck waiting, not receiving NewTimeout event")
  300. }
  301. func ensureNewEvent(
  302. ch <-chan interface{},
  303. height int64,
  304. round int,
  305. timeout time.Duration,
  306. errorMessage string) {
  307. select {
  308. case <-time.After(timeout):
  309. panic(errorMessage)
  310. case ev := <-ch:
  311. rs, ok := ev.(types.EventDataRoundState)
  312. if !ok {
  313. panic(
  314. fmt.Sprintf(
  315. "expected a EventDataRoundState, got %v.Wrong subscription channel?",
  316. reflect.TypeOf(rs)))
  317. }
  318. if rs.Height != height {
  319. panic(fmt.Sprintf("expected height %v, got %v", height, rs.Height))
  320. }
  321. if rs.Round != round {
  322. panic(fmt.Sprintf("expected round %v, got %v", round, rs.Round))
  323. }
  324. // TODO: We could check also for a step at this point!
  325. }
  326. }
  327. func ensureNewRoundStep(stepCh <-chan interface{}, height int64, round int) {
  328. ensureNewEvent(
  329. stepCh,
  330. height,
  331. round,
  332. ensureTimeout,
  333. "Timeout expired while waiting for NewStep event")
  334. }
  335. func ensureNewVote(voteCh <-chan interface{}, height int64, round int) {
  336. select {
  337. case <-time.After(ensureTimeout):
  338. break
  339. case v := <-voteCh:
  340. edv, ok := v.(types.EventDataVote)
  341. if !ok {
  342. panic(fmt.Sprintf("expected a *types.Vote, "+
  343. "got %v. wrong subscription channel?",
  344. reflect.TypeOf(v)))
  345. }
  346. vote := edv.Vote
  347. if vote.Height != height {
  348. panic(fmt.Sprintf("expected height %v, got %v", height, vote.Height))
  349. }
  350. if vote.Round != round {
  351. panic(fmt.Sprintf("expected round %v, got %v", round, vote.Round))
  352. }
  353. }
  354. }
  355. func ensureNewRound(roundCh <-chan interface{}, height int64, round int) {
  356. select {
  357. case <-time.After(ensureTimeout):
  358. panic("Timeout expired while waiting for NewRound event")
  359. case ev := <-roundCh:
  360. rs, ok := ev.(types.EventDataNewRound)
  361. if !ok {
  362. panic(
  363. fmt.Sprintf(
  364. "expected a EventDataNewRound, got %v.Wrong subscription channel?",
  365. reflect.TypeOf(rs)))
  366. }
  367. if rs.Height != height {
  368. panic(fmt.Sprintf("expected height %v, got %v", height, rs.Height))
  369. }
  370. if rs.Round != round {
  371. panic(fmt.Sprintf("expected round %v, got %v", round, rs.Round))
  372. }
  373. }
  374. }
  375. func ensureNewTimeout(timeoutCh <-chan interface{}, height int64, round int, timeout int64) {
  376. timeoutDuration := time.Duration(timeout*3) * time.Nanosecond
  377. ensureNewEvent(timeoutCh, height, round, timeoutDuration,
  378. "Timeout expired while waiting for NewTimeout event")
  379. }
  380. func ensureNewProposal(proposalCh <-chan interface{}, height int64, round int) {
  381. select {
  382. case <-time.After(ensureTimeout):
  383. panic("Timeout expired while waiting for NewProposal event")
  384. case ev := <-proposalCh:
  385. rs, ok := ev.(types.EventDataCompleteProposal)
  386. if !ok {
  387. panic(
  388. fmt.Sprintf(
  389. "expected a EventDataCompleteProposal, got %v.Wrong subscription channel?",
  390. reflect.TypeOf(rs)))
  391. }
  392. if rs.Height != height {
  393. panic(fmt.Sprintf("expected height %v, got %v", height, rs.Height))
  394. }
  395. if rs.Round != round {
  396. panic(fmt.Sprintf("expected round %v, got %v", round, rs.Round))
  397. }
  398. }
  399. }
  400. func ensureNewValidBlock(validBlockCh <-chan interface{}, height int64, round int) {
  401. ensureNewEvent(validBlockCh, height, round, ensureTimeout,
  402. "Timeout expired while waiting for NewValidBlock event")
  403. }
  404. func ensureNewBlock(blockCh <-chan interface{}, height int64) {
  405. select {
  406. case <-time.After(ensureTimeout):
  407. panic("Timeout expired while waiting for NewBlock event")
  408. case ev := <-blockCh:
  409. block, ok := ev.(types.EventDataNewBlock)
  410. if !ok {
  411. panic(fmt.Sprintf("expected a *types.EventDataNewBlock, "+
  412. "got %v. wrong subscription channel?",
  413. reflect.TypeOf(block)))
  414. }
  415. if block.Block.Height != height {
  416. panic(fmt.Sprintf("expected height %v, got %v", height, block.Block.Height))
  417. }
  418. }
  419. }
  420. func ensureNewBlockHeader(blockCh <-chan interface{}, height int64, blockHash cmn.HexBytes) {
  421. select {
  422. case <-time.After(ensureTimeout):
  423. panic("Timeout expired while waiting for NewBlockHeader event")
  424. case ev := <-blockCh:
  425. blockHeader, ok := ev.(types.EventDataNewBlockHeader)
  426. if !ok {
  427. panic(fmt.Sprintf("expected a *types.EventDataNewBlockHeader, "+
  428. "got %v. wrong subscription channel?",
  429. reflect.TypeOf(blockHeader)))
  430. }
  431. if blockHeader.Header.Height != height {
  432. panic(fmt.Sprintf("expected height %v, got %v", height, blockHeader.Header.Height))
  433. }
  434. if !bytes.Equal(blockHeader.Header.Hash(), blockHash) {
  435. panic(fmt.Sprintf("expected header %X, got %X", blockHash, blockHeader.Header.Hash()))
  436. }
  437. }
  438. }
  439. func ensureNewUnlock(unlockCh <-chan interface{}, height int64, round int) {
  440. ensureNewEvent(unlockCh, height, round, ensureTimeout,
  441. "Timeout expired while waiting for NewUnlock event")
  442. }
  443. func ensureVote(voteCh <-chan interface{}, height int64, round int,
  444. voteType types.SignedMsgType) {
  445. select {
  446. case <-time.After(ensureTimeout):
  447. panic("Timeout expired while waiting for NewVote event")
  448. case v := <-voteCh:
  449. edv, ok := v.(types.EventDataVote)
  450. if !ok {
  451. panic(fmt.Sprintf("expected a *types.Vote, "+
  452. "got %v. wrong subscription channel?",
  453. reflect.TypeOf(v)))
  454. }
  455. vote := edv.Vote
  456. if vote.Height != height {
  457. panic(fmt.Sprintf("expected height %v, got %v", height, vote.Height))
  458. }
  459. if vote.Round != round {
  460. panic(fmt.Sprintf("expected round %v, got %v", round, vote.Round))
  461. }
  462. if vote.Type != voteType {
  463. panic(fmt.Sprintf("expected type %v, got %v", voteType, vote.Type))
  464. }
  465. }
  466. }
  467. func ensureProposal(proposalCh <-chan interface{}, height int64, round int, propId types.BlockID) {
  468. select {
  469. case <-time.After(ensureTimeout):
  470. panic("Timeout expired while waiting for NewProposal event")
  471. case ev := <-proposalCh:
  472. rs, ok := ev.(types.EventDataCompleteProposal)
  473. if !ok {
  474. panic(
  475. fmt.Sprintf(
  476. "expected a EventDataCompleteProposal, got %v.Wrong subscription channel?",
  477. reflect.TypeOf(rs)))
  478. }
  479. if rs.Height != height {
  480. panic(fmt.Sprintf("expected height %v, got %v", height, rs.Height))
  481. }
  482. if rs.Round != round {
  483. panic(fmt.Sprintf("expected round %v, got %v", round, rs.Round))
  484. }
  485. if !rs.BlockID.Equals(propId) {
  486. panic("Proposed block does not match expected block")
  487. }
  488. }
  489. }
  490. func ensurePrecommit(voteCh <-chan interface{}, height int64, round int) {
  491. ensureVote(voteCh, height, round, types.PrecommitType)
  492. }
  493. func ensurePrevote(voteCh <-chan interface{}, height int64, round int) {
  494. ensureVote(voteCh, height, round, types.PrevoteType)
  495. }
  496. func ensureNewEventOnChannel(ch <-chan interface{}) {
  497. select {
  498. case <-time.After(ensureTimeout):
  499. panic("Timeout expired while waiting for new activity on the channel")
  500. case <-ch:
  501. }
  502. }
  503. //-------------------------------------------------------------------------------
  504. // consensus nets
  505. // consensusLogger is a TestingLogger which uses a different
  506. // color for each validator ("validator" key must exist).
  507. func consensusLogger() log.Logger {
  508. return log.TestingLoggerWithColorFn(func(keyvals ...interface{}) term.FgBgColor {
  509. for i := 0; i < len(keyvals)-1; i += 2 {
  510. if keyvals[i] == "validator" {
  511. return term.FgBgColor{Fg: term.Color(uint8(keyvals[i+1].(int) + 1))}
  512. }
  513. }
  514. return term.FgBgColor{}
  515. }).With("module", "consensus")
  516. }
  517. func randConsensusNet(nValidators int, testName string, tickerFunc func() TimeoutTicker, appFunc func() abci.Application, configOpts ...func(*cfg.Config)) []*ConsensusState {
  518. genDoc, privVals := randGenesisDoc(nValidators, false, 30)
  519. css := make([]*ConsensusState, nValidators)
  520. logger := consensusLogger()
  521. for i := 0; i < nValidators; i++ {
  522. stateDB := dbm.NewMemDB() // each state needs its own db
  523. state, _ := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  524. thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
  525. for _, opt := range configOpts {
  526. opt(thisConfig)
  527. }
  528. ensureDir(filepath.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal
  529. app := appFunc()
  530. vals := types.TM2PB.ValidatorUpdates(state.Validators)
  531. app.InitChain(abci.RequestInitChain{Validators: vals})
  532. css[i] = newConsensusStateWithConfig(thisConfig, state, privVals[i], app)
  533. css[i].SetTimeoutTicker(tickerFunc())
  534. css[i].SetLogger(logger.With("validator", i, "module", "consensus"))
  535. }
  536. return css
  537. }
  538. // nPeers = nValidators + nNotValidator
  539. func randConsensusNetWithPeers(nValidators, nPeers int, testName string, tickerFunc func() TimeoutTicker, appFunc func() abci.Application) []*ConsensusState {
  540. genDoc, privVals := randGenesisDoc(nValidators, false, testMinPower)
  541. css := make([]*ConsensusState, nPeers)
  542. logger := consensusLogger()
  543. for i := 0; i < nPeers; i++ {
  544. stateDB := dbm.NewMemDB() // each state needs its own db
  545. state, _ := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  546. thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
  547. ensureDir(filepath.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal
  548. var privVal types.PrivValidator
  549. if i < nValidators {
  550. privVal = privVals[i]
  551. } else {
  552. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  553. if err != nil {
  554. panic(err)
  555. }
  556. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  557. if err != nil {
  558. panic(err)
  559. }
  560. privVal = privval.GenFilePV(tempKeyFile.Name(), tempStateFile.Name())
  561. }
  562. app := appFunc()
  563. vals := types.TM2PB.ValidatorUpdates(state.Validators)
  564. app.InitChain(abci.RequestInitChain{Validators: vals})
  565. css[i] = newConsensusStateWithConfig(thisConfig, state, privVal, app)
  566. css[i].SetTimeoutTicker(tickerFunc())
  567. css[i].SetLogger(logger.With("validator", i, "module", "consensus"))
  568. }
  569. return css
  570. }
  571. func getSwitchIndex(switches []*p2p.Switch, peer p2p.Peer) int {
  572. for i, s := range switches {
  573. if peer.NodeInfo().ID() == s.NodeInfo().ID() {
  574. return i
  575. }
  576. }
  577. panic("didnt find peer in switches")
  578. return -1
  579. }
  580. //-------------------------------------------------------------------------------
  581. // genesis
  582. func randGenesisDoc(numValidators int, randPower bool, minPower int64) (*types.GenesisDoc, []types.PrivValidator) {
  583. validators := make([]types.GenesisValidator, numValidators)
  584. privValidators := make([]types.PrivValidator, numValidators)
  585. for i := 0; i < numValidators; i++ {
  586. val, privVal := types.RandValidator(randPower, minPower)
  587. validators[i] = types.GenesisValidator{
  588. PubKey: val.PubKey,
  589. Power: val.VotingPower,
  590. }
  591. privValidators[i] = privVal
  592. }
  593. sort.Sort(types.PrivValidatorsByAddress(privValidators))
  594. return &types.GenesisDoc{
  595. GenesisTime: tmtime.Now(),
  596. ChainID: config.ChainID(),
  597. Validators: validators,
  598. }, privValidators
  599. }
  600. func randGenesisState(numValidators int, randPower bool, minPower int64) (sm.State, []types.PrivValidator) {
  601. genDoc, privValidators := randGenesisDoc(numValidators, randPower, minPower)
  602. s0, _ := sm.MakeGenesisState(genDoc)
  603. return s0, privValidators
  604. }
  605. //------------------------------------
  606. // mock ticker
  607. func newMockTickerFunc(onlyOnce bool) func() TimeoutTicker {
  608. return func() TimeoutTicker {
  609. return &mockTicker{
  610. c: make(chan timeoutInfo, 10),
  611. onlyOnce: onlyOnce,
  612. }
  613. }
  614. }
  615. // mock ticker only fires on RoundStepNewHeight
  616. // and only once if onlyOnce=true
  617. type mockTicker struct {
  618. c chan timeoutInfo
  619. mtx sync.Mutex
  620. onlyOnce bool
  621. fired bool
  622. }
  623. func (m *mockTicker) Start() error {
  624. return nil
  625. }
  626. func (m *mockTicker) Stop() error {
  627. return nil
  628. }
  629. func (m *mockTicker) ScheduleTimeout(ti timeoutInfo) {
  630. m.mtx.Lock()
  631. defer m.mtx.Unlock()
  632. if m.onlyOnce && m.fired {
  633. return
  634. }
  635. if ti.Step == cstypes.RoundStepNewHeight {
  636. m.c <- ti
  637. m.fired = true
  638. }
  639. }
  640. func (m *mockTicker) Chan() <-chan timeoutInfo {
  641. return m.c
  642. }
  643. func (mockTicker) SetLogger(log.Logger) {
  644. }
  645. //------------------------------------
  646. func newCounter() abci.Application {
  647. return counter.NewCounterApplication(true)
  648. }
  649. func newPersistentKVStore() abci.Application {
  650. dir, _ := ioutil.TempDir("/tmp", "persistent-kvstore")
  651. return kvstore.NewPersistentKVStoreApplication(dir)
  652. }