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.

758 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
pubsub 2.0 (#3227) * green pubsub tests :OK: * get rid of clientToQueryMap * Subscribe and SubscribeUnbuffered * start adapting other pkgs to new pubsub * nope * rename MsgAndTags to Message * remove TagMap it does not bring any additional benefits * bring back EventSubscriber * fix test * fix data race in TestStartNextHeightCorrectly ``` Write at 0x00c0001c7418 by goroutine 796: github.com/tendermint/tendermint/consensus.TestStartNextHeightCorrectly() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:1296 +0xad testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Previous read at 0x00c0001c7418 by goroutine 858: github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1631 +0x1366 github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1476 +0x8f github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /go/src/github.com/tendermint/tendermint/consensus/state.go:667 +0xa1e github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:628 +0x794 Goroutine 796 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 testing.runTests.func1() /usr/local/go/src/testing/testing.go:1119 +0xa8 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 testing.runTests() /usr/local/go/src/testing/testing.go:1117 +0x4ee testing.(*M).Run() /usr/local/go/src/testing/testing.go:1034 +0x2ee main.main() _testmain.go:214 +0x332 Goroutine 858 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).startRoutines() /go/src/github.com/tendermint/tendermint/consensus/state.go:334 +0x221 github.com/tendermint/tendermint/consensus.startTestRound() /go/src/github.com/tendermint/tendermint/consensus/common_test.go:122 +0x63 github.com/tendermint/tendermint/consensus.TestStateFullRound1() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:255 +0x397 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ``` * fixes after my own review * fix formatting * wait 100ms before kicking a subscriber out + a test for indexer_service * fixes after my second review * no timeout * add changelog entries * fix merge conflicts * fix typos after Thane's review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * reformat code * rewrite indexer service in the attempt to fix failing test https://github.com/tendermint/tendermint/pull/3227/#issuecomment-462316527 * Revert "rewrite indexer service in the attempt to fix failing test" This reverts commit 0d9107a098230de7138abb1c201877c246e89ed1. * another attempt to fix indexer * fixes after Ethan's review * use unbuffered channel when indexing transactions Refs https://github.com/tendermint/tendermint/pull/3227#discussion_r258786716 * add a comment for EventBus#SubscribeUnbuffered * format code
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
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
6 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
  1. package consensus
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path"
  7. "sync"
  8. "testing"
  9. "time"
  10. "github.com/fortytw2/leaktest"
  11. "github.com/stretchr/testify/mock"
  12. "github.com/stretchr/testify/require"
  13. dbm "github.com/tendermint/tm-db"
  14. abciclient "github.com/tendermint/tendermint/abci/client"
  15. "github.com/tendermint/tendermint/abci/example/kvstore"
  16. abci "github.com/tendermint/tendermint/abci/types"
  17. "github.com/tendermint/tendermint/config"
  18. "github.com/tendermint/tendermint/crypto/encoding"
  19. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  20. "github.com/tendermint/tendermint/internal/mempool"
  21. mempoolv0 "github.com/tendermint/tendermint/internal/mempool/v0"
  22. "github.com/tendermint/tendermint/internal/p2p"
  23. "github.com/tendermint/tendermint/internal/p2p/p2ptest"
  24. sm "github.com/tendermint/tendermint/internal/state"
  25. statemocks "github.com/tendermint/tendermint/internal/state/mocks"
  26. "github.com/tendermint/tendermint/internal/store"
  27. "github.com/tendermint/tendermint/internal/test/factory"
  28. "github.com/tendermint/tendermint/libs/log"
  29. tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
  30. tmcons "github.com/tendermint/tendermint/proto/tendermint/consensus"
  31. "github.com/tendermint/tendermint/types"
  32. )
  33. var (
  34. defaultTestTime = time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  35. )
  36. type reactorTestSuite struct {
  37. network *p2ptest.Network
  38. states map[types.NodeID]*State
  39. reactors map[types.NodeID]*Reactor
  40. subs map[types.NodeID]types.Subscription
  41. blocksyncSubs map[types.NodeID]types.Subscription
  42. stateChannels map[types.NodeID]*p2p.Channel
  43. dataChannels map[types.NodeID]*p2p.Channel
  44. voteChannels map[types.NodeID]*p2p.Channel
  45. voteSetBitsChannels map[types.NodeID]*p2p.Channel
  46. }
  47. func chDesc(chID p2p.ChannelID) p2p.ChannelDescriptor {
  48. return p2p.ChannelDescriptor{
  49. ID: byte(chID),
  50. }
  51. }
  52. func setup(t *testing.T, numNodes int, states []*State, size int) *reactorTestSuite {
  53. t.Helper()
  54. rts := &reactorTestSuite{
  55. network: p2ptest.MakeNetwork(t, p2ptest.NetworkOptions{NumNodes: numNodes}),
  56. states: make(map[types.NodeID]*State),
  57. reactors: make(map[types.NodeID]*Reactor, numNodes),
  58. subs: make(map[types.NodeID]types.Subscription, numNodes),
  59. blocksyncSubs: make(map[types.NodeID]types.Subscription, numNodes),
  60. }
  61. rts.stateChannels = rts.network.MakeChannelsNoCleanup(t, chDesc(StateChannel), new(tmcons.Message), size)
  62. rts.dataChannels = rts.network.MakeChannelsNoCleanup(t, chDesc(DataChannel), new(tmcons.Message), size)
  63. rts.voteChannels = rts.network.MakeChannelsNoCleanup(t, chDesc(VoteChannel), new(tmcons.Message), size)
  64. rts.voteSetBitsChannels = rts.network.MakeChannelsNoCleanup(t, chDesc(VoteSetBitsChannel), new(tmcons.Message), size)
  65. _, cancel := context.WithCancel(context.Background())
  66. i := 0
  67. for nodeID, node := range rts.network.Nodes {
  68. state := states[i]
  69. reactor := NewReactor(
  70. state.Logger.With("node", nodeID),
  71. state,
  72. rts.stateChannels[nodeID],
  73. rts.dataChannels[nodeID],
  74. rts.voteChannels[nodeID],
  75. rts.voteSetBitsChannels[nodeID],
  76. node.MakePeerUpdates(t),
  77. true,
  78. )
  79. reactor.SetEventBus(state.eventBus)
  80. blocksSub, err := state.eventBus.Subscribe(context.Background(), testSubscriber, types.EventQueryNewBlock, size)
  81. require.NoError(t, err)
  82. fsSub, err := state.eventBus.Subscribe(context.Background(), testSubscriber, types.EventQueryBlockSyncStatus, size)
  83. require.NoError(t, err)
  84. rts.states[nodeID] = state
  85. rts.subs[nodeID] = blocksSub
  86. rts.reactors[nodeID] = reactor
  87. rts.blocksyncSubs[nodeID] = fsSub
  88. // simulate handle initChain in handshake
  89. if state.state.LastBlockHeight == 0 {
  90. require.NoError(t, state.blockExec.Store().Save(state.state))
  91. }
  92. require.NoError(t, reactor.Start())
  93. require.True(t, reactor.IsRunning())
  94. i++
  95. }
  96. require.Len(t, rts.reactors, numNodes)
  97. // start the in-memory network and connect all peers with each other
  98. rts.network.Start(t)
  99. t.Cleanup(func() {
  100. for nodeID, r := range rts.reactors {
  101. require.NoError(t, rts.states[nodeID].eventBus.Stop())
  102. require.NoError(t, r.Stop())
  103. require.False(t, r.IsRunning())
  104. }
  105. leaktest.Check(t)
  106. cancel()
  107. })
  108. return rts
  109. }
  110. func validateBlock(block *types.Block, activeVals map[string]struct{}) error {
  111. if block.LastCommit.Size() != len(activeVals) {
  112. return fmt.Errorf(
  113. "commit size doesn't match number of active validators. Got %d, expected %d",
  114. block.LastCommit.Size(), len(activeVals),
  115. )
  116. }
  117. for _, commitSig := range block.LastCommit.Signatures {
  118. if _, ok := activeVals[string(commitSig.ValidatorAddress)]; !ok {
  119. return fmt.Errorf("found vote for inactive validator %X", commitSig.ValidatorAddress)
  120. }
  121. }
  122. return nil
  123. }
  124. func waitForAndValidateBlock(
  125. t *testing.T,
  126. n int,
  127. activeVals map[string]struct{},
  128. blocksSubs []types.Subscription,
  129. states []*State,
  130. txs ...[]byte,
  131. ) {
  132. fn := func(j int) {
  133. msg := <-blocksSubs[j].Out()
  134. newBlock := msg.Data().(types.EventDataNewBlock).Block
  135. require.NoError(t, validateBlock(newBlock, activeVals))
  136. for _, tx := range txs {
  137. require.NoError(t, assertMempool(states[j].txNotifier).CheckTx(context.Background(), tx, nil, mempool.TxInfo{}))
  138. }
  139. }
  140. var wg sync.WaitGroup
  141. wg.Add(n)
  142. for i := 0; i < n; i++ {
  143. go func(j int) {
  144. fn(j)
  145. wg.Done()
  146. }(i)
  147. }
  148. wg.Wait()
  149. }
  150. func waitForAndValidateBlockWithTx(
  151. t *testing.T,
  152. n int,
  153. activeVals map[string]struct{},
  154. blocksSubs []types.Subscription,
  155. states []*State,
  156. txs ...[]byte,
  157. ) {
  158. fn := func(j int) {
  159. ntxs := 0
  160. BLOCK_TX_LOOP:
  161. for {
  162. msg := <-blocksSubs[j].Out()
  163. newBlock := msg.Data().(types.EventDataNewBlock).Block
  164. require.NoError(t, validateBlock(newBlock, activeVals))
  165. // check that txs match the txs we're waiting for.
  166. // note they could be spread over multiple blocks,
  167. // but they should be in order.
  168. for _, tx := range newBlock.Data.Txs {
  169. require.EqualValues(t, txs[ntxs], tx)
  170. ntxs++
  171. }
  172. if ntxs == len(txs) {
  173. break BLOCK_TX_LOOP
  174. }
  175. }
  176. }
  177. var wg sync.WaitGroup
  178. wg.Add(n)
  179. for i := 0; i < n; i++ {
  180. go func(j int) {
  181. fn(j)
  182. wg.Done()
  183. }(i)
  184. }
  185. wg.Wait()
  186. }
  187. func waitForBlockWithUpdatedValsAndValidateIt(
  188. t *testing.T,
  189. n int,
  190. updatedVals map[string]struct{},
  191. blocksSubs []types.Subscription,
  192. css []*State,
  193. ) {
  194. fn := func(j int) {
  195. var newBlock *types.Block
  196. LOOP:
  197. for {
  198. msg := <-blocksSubs[j].Out()
  199. newBlock = msg.Data().(types.EventDataNewBlock).Block
  200. if newBlock.LastCommit.Size() == len(updatedVals) {
  201. break LOOP
  202. }
  203. }
  204. require.NoError(t, validateBlock(newBlock, updatedVals))
  205. }
  206. var wg sync.WaitGroup
  207. wg.Add(n)
  208. for i := 0; i < n; i++ {
  209. go func(j int) {
  210. fn(j)
  211. wg.Done()
  212. }(i)
  213. }
  214. wg.Wait()
  215. }
  216. func ensureBlockSyncStatus(t *testing.T, msg tmpubsub.Message, complete bool, height int64) {
  217. t.Helper()
  218. status, ok := msg.Data().(types.EventDataBlockSyncStatus)
  219. require.True(t, ok)
  220. require.Equal(t, complete, status.Complete)
  221. require.Equal(t, height, status.Height)
  222. }
  223. func TestReactorBasic(t *testing.T) {
  224. cfg := configSetup(t)
  225. n := 4
  226. states, cleanup := randConsensusState(t,
  227. cfg, n, "consensus_reactor_test",
  228. newMockTickerFunc(true), newKVStore)
  229. t.Cleanup(cleanup)
  230. rts := setup(t, n, states, 100) // buffer must be large enough to not deadlock
  231. for _, reactor := range rts.reactors {
  232. state := reactor.state.GetState()
  233. reactor.SwitchToConsensus(state, false)
  234. }
  235. var wg sync.WaitGroup
  236. for _, sub := range rts.subs {
  237. wg.Add(1)
  238. // wait till everyone makes the first new block
  239. go func(s types.Subscription) {
  240. defer wg.Done()
  241. <-s.Out()
  242. }(sub)
  243. }
  244. wg.Wait()
  245. for _, sub := range rts.blocksyncSubs {
  246. wg.Add(1)
  247. // wait till everyone makes the consensus switch
  248. go func(s types.Subscription) {
  249. defer wg.Done()
  250. msg := <-s.Out()
  251. ensureBlockSyncStatus(t, msg, true, 0)
  252. }(sub)
  253. }
  254. wg.Wait()
  255. }
  256. func TestReactorWithEvidence(t *testing.T) {
  257. cfg := configSetup(t)
  258. n := 4
  259. testName := "consensus_reactor_test"
  260. tickerFunc := newMockTickerFunc(true)
  261. appFunc := newKVStore
  262. genDoc, privVals := factory.RandGenesisDoc(cfg, n, false, 30)
  263. states := make([]*State, n)
  264. logger := consensusLogger()
  265. for i := 0; i < n; i++ {
  266. stateDB := dbm.NewMemDB() // each state needs its own db
  267. stateStore := sm.NewStore(stateDB)
  268. state, err := sm.MakeGenesisState(genDoc)
  269. require.NoError(t, err)
  270. thisConfig, err := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
  271. require.NoError(t, err)
  272. defer os.RemoveAll(thisConfig.RootDir)
  273. ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal
  274. app := appFunc()
  275. vals := types.TM2PB.ValidatorUpdates(state.Validators)
  276. app.InitChain(abci.RequestInitChain{Validators: vals})
  277. pv := privVals[i]
  278. blockDB := dbm.NewMemDB()
  279. blockStore := store.NewBlockStore(blockDB)
  280. // one for mempool, one for consensus
  281. mtx := new(tmsync.Mutex)
  282. proxyAppConnMem := abciclient.NewLocalClient(mtx, app)
  283. proxyAppConnCon := abciclient.NewLocalClient(mtx, app)
  284. mempool := mempoolv0.NewCListMempool(thisConfig.Mempool, proxyAppConnMem, 0)
  285. mempool.SetLogger(log.TestingLogger().With("module", "mempool"))
  286. if thisConfig.Consensus.WaitForTxs() {
  287. mempool.EnableTxsAvailable()
  288. }
  289. // mock the evidence pool
  290. // everyone includes evidence of another double signing
  291. vIdx := (i + 1) % n
  292. ev := types.NewMockDuplicateVoteEvidenceWithValidator(1, defaultTestTime, privVals[vIdx], cfg.ChainID())
  293. evpool := &statemocks.EvidencePool{}
  294. evpool.On("CheckEvidence", mock.AnythingOfType("types.EvidenceList")).Return(nil)
  295. evpool.On("PendingEvidence", mock.AnythingOfType("int64")).Return([]types.Evidence{
  296. ev}, int64(len(ev.Bytes())))
  297. evpool.On("Update", mock.AnythingOfType("state.State"), mock.AnythingOfType("types.EvidenceList")).Return()
  298. evpool2 := sm.EmptyEvidencePool{}
  299. blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyAppConnCon, mempool, evpool, blockStore)
  300. cs := NewState(thisConfig.Consensus, state, blockExec, blockStore, mempool, evpool2)
  301. cs.SetLogger(log.TestingLogger().With("module", "consensus"))
  302. cs.SetPrivValidator(pv)
  303. eventBus := types.NewEventBus()
  304. eventBus.SetLogger(log.TestingLogger().With("module", "events"))
  305. err = eventBus.Start()
  306. require.NoError(t, err)
  307. cs.SetEventBus(eventBus)
  308. cs.SetTimeoutTicker(tickerFunc())
  309. cs.SetLogger(logger.With("validator", i, "module", "consensus"))
  310. states[i] = cs
  311. }
  312. rts := setup(t, n, states, 100) // buffer must be large enough to not deadlock
  313. for _, reactor := range rts.reactors {
  314. state := reactor.state.GetState()
  315. reactor.SwitchToConsensus(state, false)
  316. }
  317. var wg sync.WaitGroup
  318. for _, sub := range rts.subs {
  319. wg.Add(1)
  320. // We expect for each validator that is the proposer to propose one piece of
  321. // evidence.
  322. go func(s types.Subscription) {
  323. msg := <-s.Out()
  324. block := msg.Data().(types.EventDataNewBlock).Block
  325. require.Len(t, block.Evidence.Evidence, 1)
  326. wg.Done()
  327. }(sub)
  328. }
  329. wg.Wait()
  330. }
  331. func TestReactorCreatesBlockWhenEmptyBlocksFalse(t *testing.T) {
  332. cfg := configSetup(t)
  333. n := 4
  334. states, cleanup := randConsensusState(
  335. t,
  336. cfg,
  337. n,
  338. "consensus_reactor_test",
  339. newMockTickerFunc(true),
  340. newKVStore,
  341. func(c *config.Config) {
  342. c.Consensus.CreateEmptyBlocks = false
  343. },
  344. )
  345. t.Cleanup(cleanup)
  346. rts := setup(t, n, states, 100) // buffer must be large enough to not deadlock
  347. for _, reactor := range rts.reactors {
  348. state := reactor.state.GetState()
  349. reactor.SwitchToConsensus(state, false)
  350. }
  351. // send a tx
  352. require.NoError(
  353. t,
  354. assertMempool(states[3].txNotifier).CheckTx(
  355. context.Background(),
  356. []byte{1, 2, 3},
  357. nil,
  358. mempool.TxInfo{},
  359. ),
  360. )
  361. var wg sync.WaitGroup
  362. for _, sub := range rts.subs {
  363. wg.Add(1)
  364. // wait till everyone makes the first new block
  365. go func(s types.Subscription) {
  366. <-s.Out()
  367. wg.Done()
  368. }(sub)
  369. }
  370. wg.Wait()
  371. }
  372. func TestReactorRecordsVotesAndBlockParts(t *testing.T) {
  373. cfg := configSetup(t)
  374. n := 4
  375. states, cleanup := randConsensusState(t,
  376. cfg, n, "consensus_reactor_test",
  377. newMockTickerFunc(true), newKVStore)
  378. t.Cleanup(cleanup)
  379. rts := setup(t, n, states, 100) // buffer must be large enough to not deadlock
  380. for _, reactor := range rts.reactors {
  381. state := reactor.state.GetState()
  382. reactor.SwitchToConsensus(state, false)
  383. }
  384. var wg sync.WaitGroup
  385. for _, sub := range rts.subs {
  386. wg.Add(1)
  387. // wait till everyone makes the first new block
  388. go func(s types.Subscription) {
  389. <-s.Out()
  390. wg.Done()
  391. }(sub)
  392. }
  393. wg.Wait()
  394. // Require at least one node to have sent block parts, but we can't know which
  395. // peer sent it.
  396. require.Eventually(
  397. t,
  398. func() bool {
  399. for _, reactor := range rts.reactors {
  400. for _, ps := range reactor.peers {
  401. if ps.BlockPartsSent() > 0 {
  402. return true
  403. }
  404. }
  405. }
  406. return false
  407. },
  408. time.Second,
  409. 10*time.Millisecond,
  410. "number of block parts sent should've increased",
  411. )
  412. nodeID := rts.network.RandomNode().NodeID
  413. reactor := rts.reactors[nodeID]
  414. peers := rts.network.Peers(nodeID)
  415. ps, ok := reactor.GetPeerState(peers[0].NodeID)
  416. require.True(t, ok)
  417. require.NotNil(t, ps)
  418. require.Greater(t, ps.VotesSent(), 0, "number of votes sent should've increased")
  419. }
  420. func TestReactorVotingPowerChange(t *testing.T) {
  421. cfg := configSetup(t)
  422. n := 4
  423. states, cleanup := randConsensusState(
  424. t,
  425. cfg,
  426. n,
  427. "consensus_voting_power_changes_test",
  428. newMockTickerFunc(true),
  429. newPersistentKVStore,
  430. )
  431. t.Cleanup(cleanup)
  432. rts := setup(t, n, states, 100) // buffer must be large enough to not deadlock
  433. for _, reactor := range rts.reactors {
  434. state := reactor.state.GetState()
  435. reactor.SwitchToConsensus(state, false)
  436. }
  437. // map of active validators
  438. activeVals := make(map[string]struct{})
  439. for i := 0; i < n; i++ {
  440. pubKey, err := states[i].privValidator.GetPubKey(context.Background())
  441. require.NoError(t, err)
  442. addr := pubKey.Address()
  443. activeVals[string(addr)] = struct{}{}
  444. }
  445. var wg sync.WaitGroup
  446. for _, sub := range rts.subs {
  447. wg.Add(1)
  448. // wait till everyone makes the first new block
  449. go func(s types.Subscription) {
  450. <-s.Out()
  451. wg.Done()
  452. }(sub)
  453. }
  454. wg.Wait()
  455. blocksSubs := []types.Subscription{}
  456. for _, sub := range rts.subs {
  457. blocksSubs = append(blocksSubs, sub)
  458. }
  459. val1PubKey, err := states[0].privValidator.GetPubKey(context.Background())
  460. require.NoError(t, err)
  461. val1PubKeyABCI, err := encoding.PubKeyToProto(val1PubKey)
  462. require.NoError(t, err)
  463. updateValidatorTx := kvstore.MakeValSetChangeTx(val1PubKeyABCI, 25)
  464. previousTotalVotingPower := states[0].GetRoundState().LastValidators.TotalVotingPower()
  465. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states, updateValidatorTx)
  466. waitForAndValidateBlockWithTx(t, n, activeVals, blocksSubs, states, updateValidatorTx)
  467. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states)
  468. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states)
  469. require.NotEqualf(
  470. t, previousTotalVotingPower, states[0].GetRoundState().LastValidators.TotalVotingPower(),
  471. "expected voting power to change (before: %d, after: %d)",
  472. previousTotalVotingPower,
  473. states[0].GetRoundState().LastValidators.TotalVotingPower(),
  474. )
  475. updateValidatorTx = kvstore.MakeValSetChangeTx(val1PubKeyABCI, 2)
  476. previousTotalVotingPower = states[0].GetRoundState().LastValidators.TotalVotingPower()
  477. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states, updateValidatorTx)
  478. waitForAndValidateBlockWithTx(t, n, activeVals, blocksSubs, states, updateValidatorTx)
  479. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states)
  480. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states)
  481. require.NotEqualf(
  482. t, states[0].GetRoundState().LastValidators.TotalVotingPower(), previousTotalVotingPower,
  483. "expected voting power to change (before: %d, after: %d)",
  484. previousTotalVotingPower, states[0].GetRoundState().LastValidators.TotalVotingPower(),
  485. )
  486. updateValidatorTx = kvstore.MakeValSetChangeTx(val1PubKeyABCI, 26)
  487. previousTotalVotingPower = states[0].GetRoundState().LastValidators.TotalVotingPower()
  488. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states, updateValidatorTx)
  489. waitForAndValidateBlockWithTx(t, n, activeVals, blocksSubs, states, updateValidatorTx)
  490. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states)
  491. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states)
  492. require.NotEqualf(
  493. t, previousTotalVotingPower, states[0].GetRoundState().LastValidators.TotalVotingPower(),
  494. "expected voting power to change (before: %d, after: %d)",
  495. previousTotalVotingPower,
  496. states[0].GetRoundState().LastValidators.TotalVotingPower(),
  497. )
  498. }
  499. func TestReactorValidatorSetChanges(t *testing.T) {
  500. cfg := configSetup(t)
  501. nPeers := 7
  502. nVals := 4
  503. states, _, _, cleanup := randConsensusNetWithPeers(
  504. cfg,
  505. nVals,
  506. nPeers,
  507. "consensus_val_set_changes_test",
  508. newMockTickerFunc(true),
  509. newPersistentKVStoreWithPath,
  510. )
  511. t.Cleanup(cleanup)
  512. rts := setup(t, nPeers, states, 100) // buffer must be large enough to not deadlock
  513. for _, reactor := range rts.reactors {
  514. state := reactor.state.GetState()
  515. reactor.SwitchToConsensus(state, false)
  516. }
  517. // map of active validators
  518. activeVals := make(map[string]struct{})
  519. for i := 0; i < nVals; i++ {
  520. pubKey, err := states[i].privValidator.GetPubKey(context.Background())
  521. require.NoError(t, err)
  522. activeVals[string(pubKey.Address())] = struct{}{}
  523. }
  524. var wg sync.WaitGroup
  525. for _, sub := range rts.subs {
  526. wg.Add(1)
  527. // wait till everyone makes the first new block
  528. go func(s types.Subscription) {
  529. <-s.Out()
  530. wg.Done()
  531. }(sub)
  532. }
  533. wg.Wait()
  534. newValidatorPubKey1, err := states[nVals].privValidator.GetPubKey(context.Background())
  535. require.NoError(t, err)
  536. valPubKey1ABCI, err := encoding.PubKeyToProto(newValidatorPubKey1)
  537. require.NoError(t, err)
  538. newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower)
  539. blocksSubs := []types.Subscription{}
  540. for _, sub := range rts.subs {
  541. blocksSubs = append(blocksSubs, sub)
  542. }
  543. // wait till everyone makes block 2
  544. // ensure the commit includes all validators
  545. // send newValTx to change vals in block 3
  546. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states, newValidatorTx1)
  547. // wait till everyone makes block 3.
  548. // it includes the commit for block 2, which is by the original validator set
  549. waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, states, newValidatorTx1)
  550. // wait till everyone makes block 4.
  551. // it includes the commit for block 3, which is by the original validator set
  552. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states)
  553. // the commits for block 4 should be with the updated validator set
  554. activeVals[string(newValidatorPubKey1.Address())] = struct{}{}
  555. // wait till everyone makes block 5
  556. // it includes the commit for block 4, which should have the updated validator set
  557. waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, states)
  558. updateValidatorPubKey1, err := states[nVals].privValidator.GetPubKey(context.Background())
  559. require.NoError(t, err)
  560. updatePubKey1ABCI, err := encoding.PubKeyToProto(updateValidatorPubKey1)
  561. require.NoError(t, err)
  562. updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25)
  563. previousTotalVotingPower := states[nVals].GetRoundState().LastValidators.TotalVotingPower()
  564. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states, updateValidatorTx1)
  565. waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, states, updateValidatorTx1)
  566. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states)
  567. waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, states)
  568. require.NotEqualf(
  569. t, states[nVals].GetRoundState().LastValidators.TotalVotingPower(), previousTotalVotingPower,
  570. "expected voting power to change (before: %d, after: %d)",
  571. previousTotalVotingPower, states[nVals].GetRoundState().LastValidators.TotalVotingPower(),
  572. )
  573. newValidatorPubKey2, err := states[nVals+1].privValidator.GetPubKey(context.Background())
  574. require.NoError(t, err)
  575. newVal2ABCI, err := encoding.PubKeyToProto(newValidatorPubKey2)
  576. require.NoError(t, err)
  577. newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower)
  578. newValidatorPubKey3, err := states[nVals+2].privValidator.GetPubKey(context.Background())
  579. require.NoError(t, err)
  580. newVal3ABCI, err := encoding.PubKeyToProto(newValidatorPubKey3)
  581. require.NoError(t, err)
  582. newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower)
  583. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states, newValidatorTx2, newValidatorTx3)
  584. waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, states, newValidatorTx2, newValidatorTx3)
  585. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states)
  586. activeVals[string(newValidatorPubKey2.Address())] = struct{}{}
  587. activeVals[string(newValidatorPubKey3.Address())] = struct{}{}
  588. waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, states)
  589. removeValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, 0)
  590. removeValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, 0)
  591. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states, removeValidatorTx2, removeValidatorTx3)
  592. waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, states, removeValidatorTx2, removeValidatorTx3)
  593. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states)
  594. delete(activeVals, string(newValidatorPubKey2.Address()))
  595. delete(activeVals, string(newValidatorPubKey3.Address()))
  596. waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, states)
  597. }