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.

714 lines
21 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
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
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/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 ensureNewRound(roundCh <-chan interface{}, height int64, round int) {
  328. select {
  329. case <-time.After(ensureTimeout):
  330. panic("Timeout expired while waiting for NewRound event")
  331. case ev := <-roundCh:
  332. rs, ok := ev.(types.EventDataNewRound)
  333. if !ok {
  334. panic(
  335. fmt.Sprintf(
  336. "expected a EventDataNewRound, got %v.Wrong subscription channel?",
  337. reflect.TypeOf(rs)))
  338. }
  339. if rs.Height != height {
  340. panic(fmt.Sprintf("expected height %v, got %v", height, rs.Height))
  341. }
  342. if rs.Round != round {
  343. panic(fmt.Sprintf("expected round %v, got %v", round, rs.Round))
  344. }
  345. }
  346. }
  347. func ensureNewTimeout(timeoutCh <-chan interface{}, height int64, round int, timeout int64) {
  348. timeoutDuration := time.Duration(timeout*3) * time.Nanosecond
  349. ensureNewEvent(timeoutCh, height, round, timeoutDuration,
  350. "Timeout expired while waiting for NewTimeout event")
  351. }
  352. func ensureNewProposal(proposalCh <-chan interface{}, height int64, round int) {
  353. select {
  354. case <-time.After(ensureTimeout):
  355. panic("Timeout expired while waiting for NewProposal event")
  356. case ev := <-proposalCh:
  357. rs, ok := ev.(types.EventDataCompleteProposal)
  358. if !ok {
  359. panic(
  360. fmt.Sprintf(
  361. "expected a EventDataCompleteProposal, got %v.Wrong subscription channel?",
  362. reflect.TypeOf(rs)))
  363. }
  364. if rs.Height != height {
  365. panic(fmt.Sprintf("expected height %v, got %v", height, rs.Height))
  366. }
  367. if rs.Round != round {
  368. panic(fmt.Sprintf("expected round %v, got %v", round, rs.Round))
  369. }
  370. }
  371. }
  372. func ensureNewValidBlock(validBlockCh <-chan interface{}, height int64, round int) {
  373. ensureNewEvent(validBlockCh, height, round, ensureTimeout,
  374. "Timeout expired while waiting for NewValidBlock event")
  375. }
  376. func ensureNewBlock(blockCh <-chan interface{}, height int64) {
  377. select {
  378. case <-time.After(ensureTimeout):
  379. panic("Timeout expired while waiting for NewBlock event")
  380. case ev := <-blockCh:
  381. block, ok := ev.(types.EventDataNewBlock)
  382. if !ok {
  383. panic(fmt.Sprintf("expected a *types.EventDataNewBlock, "+
  384. "got %v. wrong subscription channel?",
  385. reflect.TypeOf(block)))
  386. }
  387. if block.Block.Height != height {
  388. panic(fmt.Sprintf("expected height %v, got %v", height, block.Block.Height))
  389. }
  390. }
  391. }
  392. func ensureNewBlockHeader(blockCh <-chan interface{}, height int64, blockHash cmn.HexBytes) {
  393. select {
  394. case <-time.After(ensureTimeout):
  395. panic("Timeout expired while waiting for NewBlockHeader event")
  396. case ev := <-blockCh:
  397. blockHeader, ok := ev.(types.EventDataNewBlockHeader)
  398. if !ok {
  399. panic(fmt.Sprintf("expected a *types.EventDataNewBlockHeader, "+
  400. "got %v. wrong subscription channel?",
  401. reflect.TypeOf(blockHeader)))
  402. }
  403. if blockHeader.Header.Height != height {
  404. panic(fmt.Sprintf("expected height %v, got %v", height, blockHeader.Header.Height))
  405. }
  406. if !bytes.Equal(blockHeader.Header.Hash(), blockHash) {
  407. panic(fmt.Sprintf("expected header %X, got %X", blockHash, blockHeader.Header.Hash()))
  408. }
  409. }
  410. }
  411. func ensureNewUnlock(unlockCh <-chan interface{}, height int64, round int) {
  412. ensureNewEvent(unlockCh, height, round, ensureTimeout,
  413. "Timeout expired while waiting for NewUnlock event")
  414. }
  415. func ensureVote(voteCh <-chan interface{}, height int64, round int,
  416. voteType types.SignedMsgType) {
  417. select {
  418. case <-time.After(ensureTimeout):
  419. panic("Timeout expired while waiting for NewVote event")
  420. case v := <-voteCh:
  421. edv, ok := v.(types.EventDataVote)
  422. if !ok {
  423. panic(fmt.Sprintf("expected a *types.Vote, "+
  424. "got %v. wrong subscription channel?",
  425. reflect.TypeOf(v)))
  426. }
  427. vote := edv.Vote
  428. if vote.Height != height {
  429. panic(fmt.Sprintf("expected height %v, got %v", height, vote.Height))
  430. }
  431. if vote.Round != round {
  432. panic(fmt.Sprintf("expected round %v, got %v", round, vote.Round))
  433. }
  434. if vote.Type != voteType {
  435. panic(fmt.Sprintf("expected type %v, got %v", voteType, vote.Type))
  436. }
  437. }
  438. }
  439. func ensureProposal(proposalCh <-chan interface{}, height int64, round int, propId types.BlockID) {
  440. select {
  441. case <-time.After(ensureTimeout):
  442. panic("Timeout expired while waiting for NewProposal event")
  443. case ev := <-proposalCh:
  444. rs, ok := ev.(types.EventDataCompleteProposal)
  445. if !ok {
  446. panic(
  447. fmt.Sprintf(
  448. "expected a EventDataCompleteProposal, got %v.Wrong subscription channel?",
  449. reflect.TypeOf(rs)))
  450. }
  451. if rs.Height != height {
  452. panic(fmt.Sprintf("expected height %v, got %v", height, rs.Height))
  453. }
  454. if rs.Round != round {
  455. panic(fmt.Sprintf("expected round %v, got %v", round, rs.Round))
  456. }
  457. if !rs.BlockID.Equals(propId) {
  458. panic("Proposed block does not match expected block")
  459. }
  460. }
  461. }
  462. func ensurePrecommit(voteCh <-chan interface{}, height int64, round int) {
  463. ensureVote(voteCh, height, round, types.PrecommitType)
  464. }
  465. func ensurePrevote(voteCh <-chan interface{}, height int64, round int) {
  466. ensureVote(voteCh, height, round, types.PrevoteType)
  467. }
  468. func ensureNewEventOnChannel(ch <-chan interface{}) {
  469. select {
  470. case <-time.After(ensureTimeout):
  471. panic("Timeout expired while waiting for new activity on the channel")
  472. case <-ch:
  473. }
  474. }
  475. //-------------------------------------------------------------------------------
  476. // consensus nets
  477. // consensusLogger is a TestingLogger which uses a different
  478. // color for each validator ("validator" key must exist).
  479. func consensusLogger() log.Logger {
  480. return log.TestingLoggerWithColorFn(func(keyvals ...interface{}) term.FgBgColor {
  481. for i := 0; i < len(keyvals)-1; i += 2 {
  482. if keyvals[i] == "validator" {
  483. return term.FgBgColor{Fg: term.Color(uint8(keyvals[i+1].(int) + 1))}
  484. }
  485. }
  486. return term.FgBgColor{}
  487. }).With("module", "consensus")
  488. }
  489. func randConsensusNet(nValidators int, testName string, tickerFunc func() TimeoutTicker, appFunc func() abci.Application, configOpts ...func(*cfg.Config)) []*ConsensusState {
  490. genDoc, privVals := randGenesisDoc(nValidators, false, 30)
  491. css := make([]*ConsensusState, nValidators)
  492. logger := consensusLogger()
  493. for i := 0; i < nValidators; i++ {
  494. stateDB := dbm.NewMemDB() // each state needs its own db
  495. state, _ := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  496. thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
  497. for _, opt := range configOpts {
  498. opt(thisConfig)
  499. }
  500. ensureDir(filepath.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal
  501. app := appFunc()
  502. vals := types.TM2PB.ValidatorUpdates(state.Validators)
  503. app.InitChain(abci.RequestInitChain{Validators: vals})
  504. css[i] = newConsensusStateWithConfig(thisConfig, state, privVals[i], app)
  505. css[i].SetTimeoutTicker(tickerFunc())
  506. css[i].SetLogger(logger.With("validator", i, "module", "consensus"))
  507. }
  508. return css
  509. }
  510. // nPeers = nValidators + nNotValidator
  511. func randConsensusNetWithPeers(nValidators, nPeers int, testName string, tickerFunc func() TimeoutTicker, appFunc func() abci.Application) []*ConsensusState {
  512. genDoc, privVals := randGenesisDoc(nValidators, false, testMinPower)
  513. css := make([]*ConsensusState, nPeers)
  514. logger := consensusLogger()
  515. for i := 0; i < nPeers; i++ {
  516. stateDB := dbm.NewMemDB() // each state needs its own db
  517. state, _ := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  518. thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
  519. ensureDir(filepath.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal
  520. var privVal types.PrivValidator
  521. if i < nValidators {
  522. privVal = privVals[i]
  523. } else {
  524. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  525. if err != nil {
  526. panic(err)
  527. }
  528. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  529. if err != nil {
  530. panic(err)
  531. }
  532. privVal = privval.GenFilePV(tempKeyFile.Name(), tempStateFile.Name())
  533. }
  534. app := appFunc()
  535. vals := types.TM2PB.ValidatorUpdates(state.Validators)
  536. app.InitChain(abci.RequestInitChain{Validators: vals})
  537. css[i] = newConsensusStateWithConfig(thisConfig, state, privVal, app)
  538. css[i].SetTimeoutTicker(tickerFunc())
  539. css[i].SetLogger(logger.With("validator", i, "module", "consensus"))
  540. }
  541. return css
  542. }
  543. func getSwitchIndex(switches []*p2p.Switch, peer p2p.Peer) int {
  544. for i, s := range switches {
  545. if peer.NodeInfo().ID() == s.NodeInfo().ID() {
  546. return i
  547. }
  548. }
  549. panic("didnt find peer in switches")
  550. return -1
  551. }
  552. //-------------------------------------------------------------------------------
  553. // genesis
  554. func randGenesisDoc(numValidators int, randPower bool, minPower int64) (*types.GenesisDoc, []types.PrivValidator) {
  555. validators := make([]types.GenesisValidator, numValidators)
  556. privValidators := make([]types.PrivValidator, numValidators)
  557. for i := 0; i < numValidators; i++ {
  558. val, privVal := types.RandValidator(randPower, minPower)
  559. validators[i] = types.GenesisValidator{
  560. PubKey: val.PubKey,
  561. Power: val.VotingPower,
  562. }
  563. privValidators[i] = privVal
  564. }
  565. sort.Sort(types.PrivValidatorsByAddress(privValidators))
  566. return &types.GenesisDoc{
  567. GenesisTime: tmtime.Now(),
  568. ChainID: config.ChainID(),
  569. Validators: validators,
  570. }, privValidators
  571. }
  572. func randGenesisState(numValidators int, randPower bool, minPower int64) (sm.State, []types.PrivValidator) {
  573. genDoc, privValidators := randGenesisDoc(numValidators, randPower, minPower)
  574. s0, _ := sm.MakeGenesisState(genDoc)
  575. return s0, privValidators
  576. }
  577. //------------------------------------
  578. // mock ticker
  579. func newMockTickerFunc(onlyOnce bool) func() TimeoutTicker {
  580. return func() TimeoutTicker {
  581. return &mockTicker{
  582. c: make(chan timeoutInfo, 10),
  583. onlyOnce: onlyOnce,
  584. }
  585. }
  586. }
  587. // mock ticker only fires on RoundStepNewHeight
  588. // and only once if onlyOnce=true
  589. type mockTicker struct {
  590. c chan timeoutInfo
  591. mtx sync.Mutex
  592. onlyOnce bool
  593. fired bool
  594. }
  595. func (m *mockTicker) Start() error {
  596. return nil
  597. }
  598. func (m *mockTicker) Stop() error {
  599. return nil
  600. }
  601. func (m *mockTicker) ScheduleTimeout(ti timeoutInfo) {
  602. m.mtx.Lock()
  603. defer m.mtx.Unlock()
  604. if m.onlyOnce && m.fired {
  605. return
  606. }
  607. if ti.Step == cstypes.RoundStepNewHeight {
  608. m.c <- ti
  609. m.fired = true
  610. }
  611. }
  612. func (m *mockTicker) Chan() <-chan timeoutInfo {
  613. return m.c
  614. }
  615. func (mockTicker) SetLogger(log.Logger) {
  616. }
  617. //------------------------------------
  618. func newCounter() abci.Application {
  619. return counter.NewCounterApplication(true)
  620. }
  621. func newPersistentKVStore() abci.Application {
  622. dir, _ := ioutil.TempDir("/tmp", "persistent-kvstore")
  623. return kvstore.NewPersistentKVStoreApplication(dir)
  624. }