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.

680 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
6 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
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 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. "sort"
  10. "sync"
  11. "testing"
  12. "time"
  13. "github.com/go-kit/kit/log/term"
  14. abcicli "github.com/tendermint/tendermint/abci/client"
  15. "github.com/tendermint/tendermint/abci/example/counter"
  16. "github.com/tendermint/tendermint/abci/example/kvstore"
  17. abci "github.com/tendermint/tendermint/abci/types"
  18. bc "github.com/tendermint/tendermint/blockchain"
  19. cfg "github.com/tendermint/tendermint/config"
  20. cstypes "github.com/tendermint/tendermint/consensus/types"
  21. cmn "github.com/tendermint/tendermint/libs/common"
  22. dbm "github.com/tendermint/tendermint/libs/db"
  23. "github.com/tendermint/tendermint/libs/log"
  24. tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
  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. func subscribeToVoter(cs *ConsensusState, addr []byte) <-chan tmpubsub.Message {
  192. votesSub, err := cs.eventBus.Subscribe(context.Background(), testSubscriber, types.EventQueryVote)
  193. if err != nil {
  194. panic(fmt.Sprintf("failed to subscribe %s to %v", testSubscriber, types.EventQueryVote))
  195. }
  196. ch := make(chan tmpubsub.Message)
  197. go func() {
  198. for msg := range votesSub.Out() {
  199. vote := msg.Data().(types.EventDataVote)
  200. // we only fire for our own votes
  201. if bytes.Equal(addr, vote.Vote.ValidatorAddress) {
  202. ch <- msg
  203. }
  204. }
  205. }()
  206. return ch
  207. }
  208. //-------------------------------------------------------------------------------
  209. // consensus states
  210. func newConsensusState(state sm.State, pv types.PrivValidator, app abci.Application) *ConsensusState {
  211. return newConsensusStateWithConfig(config, state, pv, app)
  212. }
  213. func newConsensusStateWithConfig(thisConfig *cfg.Config, state sm.State, pv types.PrivValidator, app abci.Application) *ConsensusState {
  214. blockDB := dbm.NewMemDB()
  215. return newConsensusStateWithConfigAndBlockStore(thisConfig, state, pv, app, blockDB)
  216. }
  217. func newConsensusStateWithConfigAndBlockStore(thisConfig *cfg.Config, state sm.State, pv types.PrivValidator, app abci.Application, blockDB dbm.DB) *ConsensusState {
  218. // Get BlockStore
  219. blockStore := bc.NewBlockStore(blockDB)
  220. // one for mempool, one for consensus
  221. mtx := new(sync.Mutex)
  222. proxyAppConnMem := abcicli.NewLocalClient(mtx, app)
  223. proxyAppConnCon := abcicli.NewLocalClient(mtx, app)
  224. // Make Mempool
  225. mempool := mempl.NewMempool(thisConfig.Mempool, proxyAppConnMem, 0)
  226. mempool.SetLogger(log.TestingLogger().With("module", "mempool"))
  227. if thisConfig.Consensus.WaitForTxs() {
  228. mempool.EnableTxsAvailable()
  229. }
  230. // mock the evidence pool
  231. evpool := sm.MockEvidencePool{}
  232. // Make ConsensusState
  233. stateDB := dbm.NewMemDB()
  234. blockExec := sm.NewBlockExecutor(stateDB, log.TestingLogger(), proxyAppConnCon, mempool, evpool)
  235. cs := NewConsensusState(thisConfig.Consensus, state, blockExec, blockStore, mempool, evpool)
  236. cs.SetLogger(log.TestingLogger().With("module", "consensus"))
  237. cs.SetPrivValidator(pv)
  238. eventBus := types.NewEventBus()
  239. eventBus.SetLogger(log.TestingLogger().With("module", "events"))
  240. eventBus.Start()
  241. cs.SetEventBus(eventBus)
  242. return cs
  243. }
  244. func loadPrivValidator(config *cfg.Config) *privval.FilePV {
  245. privValidatorKeyFile := config.PrivValidatorKeyFile()
  246. ensureDir(filepath.Dir(privValidatorKeyFile), 0700)
  247. privValidatorStateFile := config.PrivValidatorStateFile()
  248. privValidator := privval.LoadOrGenFilePV(privValidatorKeyFile, privValidatorStateFile)
  249. privValidator.Reset()
  250. return privValidator
  251. }
  252. func randConsensusState(nValidators int) (*ConsensusState, []*validatorStub) {
  253. // Get State
  254. state, privVals := randGenesisState(nValidators, false, 10)
  255. vss := make([]*validatorStub, nValidators)
  256. cs := newConsensusState(state, privVals[0], counter.NewCounterApplication(true))
  257. for i := 0; i < nValidators; i++ {
  258. vss[i] = NewValidatorStub(privVals[i], i)
  259. }
  260. // since cs1 starts at 1
  261. incrementHeight(vss[1:]...)
  262. return cs, vss
  263. }
  264. //-------------------------------------------------------------------------------
  265. func ensureNoNewEvent(ch <-chan tmpubsub.Message, timeout time.Duration,
  266. errorMessage string) {
  267. select {
  268. case <-time.After(timeout):
  269. break
  270. case <-ch:
  271. panic(errorMessage)
  272. }
  273. }
  274. func ensureNoNewEventOnChannel(ch <-chan tmpubsub.Message) {
  275. ensureNoNewEvent(
  276. ch,
  277. ensureTimeout,
  278. "We should be stuck waiting, not receiving new event on the channel")
  279. }
  280. func ensureNoNewRoundStep(stepCh <-chan tmpubsub.Message) {
  281. ensureNoNewEvent(
  282. stepCh,
  283. ensureTimeout,
  284. "We should be stuck waiting, not receiving NewRoundStep event")
  285. }
  286. func ensureNoNewUnlock(unlockCh <-chan tmpubsub.Message) {
  287. ensureNoNewEvent(
  288. unlockCh,
  289. ensureTimeout,
  290. "We should be stuck waiting, not receiving Unlock event")
  291. }
  292. func ensureNoNewTimeout(stepCh <-chan tmpubsub.Message, timeout int64) {
  293. timeoutDuration := time.Duration(timeout*5) * time.Nanosecond
  294. ensureNoNewEvent(
  295. stepCh,
  296. timeoutDuration,
  297. "We should be stuck waiting, not receiving NewTimeout event")
  298. }
  299. func ensureNewEvent(ch <-chan tmpubsub.Message, height int64, round int, timeout time.Duration, errorMessage string) {
  300. select {
  301. case <-time.After(timeout):
  302. panic(errorMessage)
  303. case msg := <-ch:
  304. roundStateEvent, ok := msg.Data().(types.EventDataRoundState)
  305. if !ok {
  306. panic(fmt.Sprintf("expected a EventDataRoundState, got %T. Wrong subscription channel?",
  307. msg.Data()))
  308. }
  309. if roundStateEvent.Height != height {
  310. panic(fmt.Sprintf("expected height %v, got %v", height, roundStateEvent.Height))
  311. }
  312. if roundStateEvent.Round != round {
  313. panic(fmt.Sprintf("expected round %v, got %v", round, roundStateEvent.Round))
  314. }
  315. // TODO: We could check also for a step at this point!
  316. }
  317. }
  318. func ensureNewRoundStep(stepCh <-chan tmpubsub.Message, height int64, round int) {
  319. ensureNewEvent(stepCh, height, round, ensureTimeout, "Timeout expired while waiting for NewStep event")
  320. }
  321. func ensureNewTimeout(timeoutCh <-chan tmpubsub.Message, height int64, round int, timeout int64) {
  322. timeoutDuration := time.Duration(timeout*3) * time.Nanosecond
  323. ensureNewEvent(timeoutCh, height, round, timeoutDuration,
  324. "Timeout expired while waiting for NewTimeout event")
  325. }
  326. func ensureNewProposal(proposalCh <-chan tmpubsub.Message, height int64, round int) {
  327. select {
  328. case <-time.After(ensureTimeout):
  329. panic("Timeout expired while waiting for NewProposal event")
  330. case msg := <-proposalCh:
  331. proposalEvent, ok := msg.Data().(types.EventDataCompleteProposal)
  332. if !ok {
  333. panic(fmt.Sprintf("expected a EventDataCompleteProposal, got %T. Wrong subscription channel?",
  334. msg.Data()))
  335. }
  336. if proposalEvent.Height != height {
  337. panic(fmt.Sprintf("expected height %v, got %v", height, proposalEvent.Height))
  338. }
  339. if proposalEvent.Round != round {
  340. panic(fmt.Sprintf("expected round %v, got %v", round, proposalEvent.Round))
  341. }
  342. }
  343. }
  344. func ensureNewValidBlock(validBlockCh <-chan tmpubsub.Message, height int64, round int) {
  345. ensureNewEvent(validBlockCh, height, round, ensureTimeout,
  346. "Timeout expired while waiting for NewValidBlock event")
  347. }
  348. func ensureNewBlock(blockCh <-chan tmpubsub.Message, height int64) {
  349. select {
  350. case <-time.After(ensureTimeout):
  351. panic("Timeout expired while waiting for NewBlock event")
  352. case msg := <-blockCh:
  353. blockEvent, ok := msg.Data().(types.EventDataNewBlock)
  354. if !ok {
  355. panic(fmt.Sprintf("expected a EventDataNewBlock, got %T. Wrong subscription channel?",
  356. msg.Data()))
  357. }
  358. if blockEvent.Block.Height != height {
  359. panic(fmt.Sprintf("expected height %v, got %v", height, blockEvent.Block.Height))
  360. }
  361. }
  362. }
  363. func ensureNewBlockHeader(blockCh <-chan tmpubsub.Message, height int64, blockHash cmn.HexBytes) {
  364. select {
  365. case <-time.After(ensureTimeout):
  366. panic("Timeout expired while waiting for NewBlockHeader event")
  367. case msg := <-blockCh:
  368. blockHeaderEvent, ok := msg.Data().(types.EventDataNewBlockHeader)
  369. if !ok {
  370. panic(fmt.Sprintf("expected a EventDataNewBlockHeader, got %T. Wrong subscription channel?",
  371. msg.Data()))
  372. }
  373. if blockHeaderEvent.Header.Height != height {
  374. panic(fmt.Sprintf("expected height %v, got %v", height, blockHeaderEvent.Header.Height))
  375. }
  376. if !bytes.Equal(blockHeaderEvent.Header.Hash(), blockHash) {
  377. panic(fmt.Sprintf("expected header %X, got %X", blockHash, blockHeaderEvent.Header.Hash()))
  378. }
  379. }
  380. }
  381. func ensureNewUnlock(unlockCh <-chan tmpubsub.Message, height int64, round int) {
  382. ensureNewEvent(unlockCh, height, round, ensureTimeout,
  383. "Timeout expired while waiting for NewUnlock event")
  384. }
  385. func ensureProposal(proposalCh <-chan tmpubsub.Message, height int64, round int, propID types.BlockID) {
  386. select {
  387. case <-time.After(ensureTimeout):
  388. panic("Timeout expired while waiting for NewProposal event")
  389. case msg := <-proposalCh:
  390. proposalEvent, ok := msg.Data().(types.EventDataCompleteProposal)
  391. if !ok {
  392. panic(fmt.Sprintf("expected a EventDataCompleteProposal, got %T. Wrong subscription channel?",
  393. msg.Data()))
  394. }
  395. if proposalEvent.Height != height {
  396. panic(fmt.Sprintf("expected height %v, got %v", height, proposalEvent.Height))
  397. }
  398. if proposalEvent.Round != round {
  399. panic(fmt.Sprintf("expected round %v, got %v", round, proposalEvent.Round))
  400. }
  401. if !proposalEvent.BlockID.Equals(propID) {
  402. panic("Proposed block does not match expected block")
  403. }
  404. }
  405. }
  406. func ensurePrecommit(voteCh <-chan tmpubsub.Message, height int64, round int) {
  407. ensureVote(voteCh, height, round, types.PrecommitType)
  408. }
  409. func ensurePrevote(voteCh <-chan tmpubsub.Message, height int64, round int) {
  410. ensureVote(voteCh, height, round, types.PrevoteType)
  411. }
  412. func ensureVote(voteCh <-chan tmpubsub.Message, height int64, round int,
  413. voteType types.SignedMsgType) {
  414. select {
  415. case <-time.After(ensureTimeout):
  416. panic("Timeout expired while waiting for NewVote event")
  417. case msg := <-voteCh:
  418. voteEvent, ok := msg.Data().(types.EventDataVote)
  419. if !ok {
  420. panic(fmt.Sprintf("expected a EventDataVote, got %T. Wrong subscription channel?",
  421. msg.Data()))
  422. }
  423. vote := voteEvent.Vote
  424. if vote.Height != height {
  425. panic(fmt.Sprintf("expected height %v, got %v", height, vote.Height))
  426. }
  427. if vote.Round != round {
  428. panic(fmt.Sprintf("expected round %v, got %v", round, vote.Round))
  429. }
  430. if vote.Type != voteType {
  431. panic(fmt.Sprintf("expected type %v, got %v", voteType, vote.Type))
  432. }
  433. }
  434. }
  435. func ensureNewEventOnChannel(ch <-chan tmpubsub.Message) {
  436. select {
  437. case <-time.After(ensureTimeout):
  438. panic("Timeout expired while waiting for new activity on the channel")
  439. case <-ch:
  440. }
  441. }
  442. //-------------------------------------------------------------------------------
  443. // consensus nets
  444. // consensusLogger is a TestingLogger which uses a different
  445. // color for each validator ("validator" key must exist).
  446. func consensusLogger() log.Logger {
  447. return log.TestingLoggerWithColorFn(func(keyvals ...interface{}) term.FgBgColor {
  448. for i := 0; i < len(keyvals)-1; i += 2 {
  449. if keyvals[i] == "validator" {
  450. return term.FgBgColor{Fg: term.Color(uint8(keyvals[i+1].(int) + 1))}
  451. }
  452. }
  453. return term.FgBgColor{}
  454. }).With("module", "consensus")
  455. }
  456. func randConsensusNet(nValidators int, testName string, tickerFunc func() TimeoutTicker, appFunc func() abci.Application, configOpts ...func(*cfg.Config)) []*ConsensusState {
  457. genDoc, privVals := randGenesisDoc(nValidators, false, 30)
  458. css := make([]*ConsensusState, nValidators)
  459. logger := consensusLogger()
  460. for i := 0; i < nValidators; i++ {
  461. stateDB := dbm.NewMemDB() // each state needs its own db
  462. state, _ := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  463. thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
  464. for _, opt := range configOpts {
  465. opt(thisConfig)
  466. }
  467. ensureDir(filepath.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal
  468. app := appFunc()
  469. vals := types.TM2PB.ValidatorUpdates(state.Validators)
  470. app.InitChain(abci.RequestInitChain{Validators: vals})
  471. css[i] = newConsensusStateWithConfig(thisConfig, state, privVals[i], app)
  472. css[i].SetTimeoutTicker(tickerFunc())
  473. css[i].SetLogger(logger.With("validator", i, "module", "consensus"))
  474. }
  475. return css
  476. }
  477. // nPeers = nValidators + nNotValidator
  478. func randConsensusNetWithPeers(nValidators, nPeers int, testName string, tickerFunc func() TimeoutTicker, appFunc func() abci.Application) []*ConsensusState {
  479. genDoc, privVals := randGenesisDoc(nValidators, false, testMinPower)
  480. css := make([]*ConsensusState, nPeers)
  481. logger := consensusLogger()
  482. for i := 0; i < nPeers; i++ {
  483. stateDB := dbm.NewMemDB() // each state needs its own db
  484. state, _ := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  485. thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
  486. ensureDir(filepath.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal
  487. var privVal types.PrivValidator
  488. if i < nValidators {
  489. privVal = privVals[i]
  490. } else {
  491. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  492. if err != nil {
  493. panic(err)
  494. }
  495. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  496. if err != nil {
  497. panic(err)
  498. }
  499. privVal = privval.GenFilePV(tempKeyFile.Name(), tempStateFile.Name())
  500. }
  501. app := appFunc()
  502. vals := types.TM2PB.ValidatorUpdates(state.Validators)
  503. app.InitChain(abci.RequestInitChain{Validators: vals})
  504. css[i] = newConsensusStateWithConfig(thisConfig, state, privVal, app)
  505. css[i].SetTimeoutTicker(tickerFunc())
  506. css[i].SetLogger(logger.With("validator", i, "module", "consensus"))
  507. }
  508. return css
  509. }
  510. func getSwitchIndex(switches []*p2p.Switch, peer p2p.Peer) int {
  511. for i, s := range switches {
  512. if peer.NodeInfo().ID() == s.NodeInfo().ID() {
  513. return i
  514. }
  515. }
  516. panic("didnt find peer in switches")
  517. return -1
  518. }
  519. //-------------------------------------------------------------------------------
  520. // genesis
  521. func randGenesisDoc(numValidators int, randPower bool, minPower int64) (*types.GenesisDoc, []types.PrivValidator) {
  522. validators := make([]types.GenesisValidator, numValidators)
  523. privValidators := make([]types.PrivValidator, numValidators)
  524. for i := 0; i < numValidators; i++ {
  525. val, privVal := types.RandValidator(randPower, minPower)
  526. validators[i] = types.GenesisValidator{
  527. PubKey: val.PubKey,
  528. Power: val.VotingPower,
  529. }
  530. privValidators[i] = privVal
  531. }
  532. sort.Sort(types.PrivValidatorsByAddress(privValidators))
  533. return &types.GenesisDoc{
  534. GenesisTime: tmtime.Now(),
  535. ChainID: config.ChainID(),
  536. Validators: validators,
  537. }, privValidators
  538. }
  539. func randGenesisState(numValidators int, randPower bool, minPower int64) (sm.State, []types.PrivValidator) {
  540. genDoc, privValidators := randGenesisDoc(numValidators, randPower, minPower)
  541. s0, _ := sm.MakeGenesisState(genDoc)
  542. return s0, privValidators
  543. }
  544. //------------------------------------
  545. // mock ticker
  546. func newMockTickerFunc(onlyOnce bool) func() TimeoutTicker {
  547. return func() TimeoutTicker {
  548. return &mockTicker{
  549. c: make(chan timeoutInfo, 10),
  550. onlyOnce: onlyOnce,
  551. }
  552. }
  553. }
  554. // mock ticker only fires on RoundStepNewHeight
  555. // and only once if onlyOnce=true
  556. type mockTicker struct {
  557. c chan timeoutInfo
  558. mtx sync.Mutex
  559. onlyOnce bool
  560. fired bool
  561. }
  562. func (m *mockTicker) Start() error {
  563. return nil
  564. }
  565. func (m *mockTicker) Stop() error {
  566. return nil
  567. }
  568. func (m *mockTicker) ScheduleTimeout(ti timeoutInfo) {
  569. m.mtx.Lock()
  570. defer m.mtx.Unlock()
  571. if m.onlyOnce && m.fired {
  572. return
  573. }
  574. if ti.Step == cstypes.RoundStepNewHeight {
  575. m.c <- ti
  576. m.fired = true
  577. }
  578. }
  579. func (m *mockTicker) Chan() <-chan timeoutInfo {
  580. return m.c
  581. }
  582. func (mockTicker) SetLogger(log.Logger) {
  583. }
  584. //------------------------------------
  585. func newCounter() abci.Application {
  586. return counter.NewCounterApplication(true)
  587. }
  588. func newPersistentKVStore() abci.Application {
  589. dir, _ := ioutil.TempDir("/tmp", "persistent-kvstore")
  590. return kvstore.NewPersistentKVStoreApplication(dir)
  591. }