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.

676 lines
20 KiB

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