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.

764 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. "github.com/tendermint/tendermint/internal/p2p"
  22. "github.com/tendermint/tendermint/internal/p2p/p2ptest"
  23. sm "github.com/tendermint/tendermint/internal/state"
  24. statemocks "github.com/tendermint/tendermint/internal/state/mocks"
  25. "github.com/tendermint/tendermint/internal/store"
  26. "github.com/tendermint/tendermint/internal/test/factory"
  27. "github.com/tendermint/tendermint/libs/log"
  28. tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
  29. tmcons "github.com/tendermint/tendermint/proto/tendermint/consensus"
  30. "github.com/tendermint/tendermint/types"
  31. )
  32. var (
  33. defaultTestTime = time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  34. )
  35. type reactorTestSuite struct {
  36. network *p2ptest.Network
  37. states map[types.NodeID]*State
  38. reactors map[types.NodeID]*Reactor
  39. subs map[types.NodeID]types.Subscription
  40. blocksyncSubs map[types.NodeID]types.Subscription
  41. stateChannels map[types.NodeID]*p2p.Channel
  42. dataChannels map[types.NodeID]*p2p.Channel
  43. voteChannels map[types.NodeID]*p2p.Channel
  44. voteSetBitsChannels map[types.NodeID]*p2p.Channel
  45. }
  46. func chDesc(chID p2p.ChannelID, size int) *p2p.ChannelDescriptor {
  47. return &p2p.ChannelDescriptor{
  48. ID: chID,
  49. MessageType: new(tmcons.Message),
  50. RecvBufferCapacity: size,
  51. }
  52. }
  53. func setup(t *testing.T, numNodes int, states []*State, size int) *reactorTestSuite {
  54. t.Helper()
  55. rts := &reactorTestSuite{
  56. network: p2ptest.MakeNetwork(t, p2ptest.NetworkOptions{NumNodes: numNodes}),
  57. states: make(map[types.NodeID]*State),
  58. reactors: make(map[types.NodeID]*Reactor, numNodes),
  59. subs: make(map[types.NodeID]types.Subscription, numNodes),
  60. blocksyncSubs: make(map[types.NodeID]types.Subscription, numNodes),
  61. }
  62. rts.stateChannels = rts.network.MakeChannelsNoCleanup(t, chDesc(StateChannel, size))
  63. rts.dataChannels = rts.network.MakeChannelsNoCleanup(t, chDesc(DataChannel, size))
  64. rts.voteChannels = rts.network.MakeChannelsNoCleanup(t, chDesc(VoteChannel, size))
  65. rts.voteSetBitsChannels = rts.network.MakeChannelsNoCleanup(t, chDesc(VoteSetBitsChannel, size))
  66. _, cancel := context.WithCancel(context.Background())
  67. i := 0
  68. for nodeID, node := range rts.network.Nodes {
  69. state := states[i]
  70. reactor := NewReactor(
  71. state.Logger.With("node", nodeID),
  72. state,
  73. rts.stateChannels[nodeID],
  74. rts.dataChannels[nodeID],
  75. rts.voteChannels[nodeID],
  76. rts.voteSetBitsChannels[nodeID],
  77. node.MakePeerUpdates(t),
  78. true,
  79. )
  80. reactor.SetEventBus(state.eventBus)
  81. blocksSub, err := state.eventBus.Subscribe(context.Background(), testSubscriber, types.EventQueryNewBlock, size)
  82. require.NoError(t, err)
  83. fsSub, err := state.eventBus.Subscribe(context.Background(), testSubscriber, types.EventQueryBlockSyncStatus, size)
  84. require.NoError(t, err)
  85. rts.states[nodeID] = state
  86. rts.subs[nodeID] = blocksSub
  87. rts.reactors[nodeID] = reactor
  88. rts.blocksyncSubs[nodeID] = fsSub
  89. // simulate handle initChain in handshake
  90. if state.state.LastBlockHeight == 0 {
  91. require.NoError(t, state.blockExec.Store().Save(state.state))
  92. }
  93. require.NoError(t, reactor.Start())
  94. require.True(t, reactor.IsRunning())
  95. i++
  96. }
  97. require.Len(t, rts.reactors, numNodes)
  98. // start the in-memory network and connect all peers with each other
  99. rts.network.Start(t)
  100. t.Cleanup(func() {
  101. for nodeID, r := range rts.reactors {
  102. require.NoError(t, rts.states[nodeID].eventBus.Stop())
  103. require.NoError(t, r.Stop())
  104. require.False(t, r.IsRunning())
  105. }
  106. leaktest.Check(t)
  107. cancel()
  108. })
  109. return rts
  110. }
  111. func validateBlock(block *types.Block, activeVals map[string]struct{}) error {
  112. if block.LastCommit.Size() != len(activeVals) {
  113. return fmt.Errorf(
  114. "commit size doesn't match number of active validators. Got %d, expected %d",
  115. block.LastCommit.Size(), len(activeVals),
  116. )
  117. }
  118. for _, commitSig := range block.LastCommit.Signatures {
  119. if _, ok := activeVals[string(commitSig.ValidatorAddress)]; !ok {
  120. return fmt.Errorf("found vote for inactive validator %X", commitSig.ValidatorAddress)
  121. }
  122. }
  123. return nil
  124. }
  125. func waitForAndValidateBlock(
  126. t *testing.T,
  127. n int,
  128. activeVals map[string]struct{},
  129. blocksSubs []types.Subscription,
  130. states []*State,
  131. txs ...[]byte,
  132. ) {
  133. fn := func(j int) {
  134. msg := <-blocksSubs[j].Out()
  135. newBlock := msg.Data().(types.EventDataNewBlock).Block
  136. require.NoError(t, validateBlock(newBlock, activeVals))
  137. for _, tx := range txs {
  138. require.NoError(t, assertMempool(states[j].txNotifier).CheckTx(context.Background(), tx, nil, mempool.TxInfo{}))
  139. }
  140. }
  141. var wg sync.WaitGroup
  142. wg.Add(n)
  143. for i := 0; i < n; i++ {
  144. go func(j int) {
  145. fn(j)
  146. wg.Done()
  147. }(i)
  148. }
  149. wg.Wait()
  150. }
  151. func waitForAndValidateBlockWithTx(
  152. t *testing.T,
  153. n int,
  154. activeVals map[string]struct{},
  155. blocksSubs []types.Subscription,
  156. states []*State,
  157. txs ...[]byte,
  158. ) {
  159. fn := func(j int) {
  160. ntxs := 0
  161. BLOCK_TX_LOOP:
  162. for {
  163. msg := <-blocksSubs[j].Out()
  164. newBlock := msg.Data().(types.EventDataNewBlock).Block
  165. require.NoError(t, validateBlock(newBlock, activeVals))
  166. // check that txs match the txs we're waiting for.
  167. // note they could be spread over multiple blocks,
  168. // but they should be in order.
  169. for _, tx := range newBlock.Data.Txs {
  170. require.EqualValues(t, txs[ntxs], tx)
  171. ntxs++
  172. }
  173. if ntxs == len(txs) {
  174. break BLOCK_TX_LOOP
  175. }
  176. }
  177. }
  178. var wg sync.WaitGroup
  179. wg.Add(n)
  180. for i := 0; i < n; i++ {
  181. go func(j int) {
  182. fn(j)
  183. wg.Done()
  184. }(i)
  185. }
  186. wg.Wait()
  187. }
  188. func waitForBlockWithUpdatedValsAndValidateIt(
  189. t *testing.T,
  190. n int,
  191. updatedVals map[string]struct{},
  192. blocksSubs []types.Subscription,
  193. css []*State,
  194. ) {
  195. fn := func(j int) {
  196. var newBlock *types.Block
  197. LOOP:
  198. for {
  199. msg := <-blocksSubs[j].Out()
  200. newBlock = msg.Data().(types.EventDataNewBlock).Block
  201. if newBlock.LastCommit.Size() == len(updatedVals) {
  202. break LOOP
  203. }
  204. }
  205. require.NoError(t, validateBlock(newBlock, updatedVals))
  206. }
  207. var wg sync.WaitGroup
  208. wg.Add(n)
  209. for i := 0; i < n; i++ {
  210. go func(j int) {
  211. fn(j)
  212. wg.Done()
  213. }(i)
  214. }
  215. wg.Wait()
  216. }
  217. func ensureBlockSyncStatus(t *testing.T, msg tmpubsub.Message, complete bool, height int64) {
  218. t.Helper()
  219. status, ok := msg.Data().(types.EventDataBlockSyncStatus)
  220. require.True(t, ok)
  221. require.Equal(t, complete, status.Complete)
  222. require.Equal(t, height, status.Height)
  223. }
  224. func TestReactorBasic(t *testing.T) {
  225. cfg := configSetup(t)
  226. n := 4
  227. states, cleanup := randConsensusState(t,
  228. cfg, n, "consensus_reactor_test",
  229. newMockTickerFunc(true), newKVStore)
  230. t.Cleanup(cleanup)
  231. rts := setup(t, n, states, 100) // buffer must be large enough to not deadlock
  232. for _, reactor := range rts.reactors {
  233. state := reactor.state.GetState()
  234. reactor.SwitchToConsensus(state, false)
  235. }
  236. var wg sync.WaitGroup
  237. for _, sub := range rts.subs {
  238. wg.Add(1)
  239. // wait till everyone makes the first new block
  240. go func(s types.Subscription) {
  241. defer wg.Done()
  242. <-s.Out()
  243. }(sub)
  244. }
  245. wg.Wait()
  246. for _, sub := range rts.blocksyncSubs {
  247. wg.Add(1)
  248. // wait till everyone makes the consensus switch
  249. go func(s types.Subscription) {
  250. defer wg.Done()
  251. msg := <-s.Out()
  252. ensureBlockSyncStatus(t, msg, true, 0)
  253. }(sub)
  254. }
  255. wg.Wait()
  256. }
  257. func TestReactorWithEvidence(t *testing.T) {
  258. cfg := configSetup(t)
  259. n := 4
  260. testName := "consensus_reactor_test"
  261. tickerFunc := newMockTickerFunc(true)
  262. appFunc := newKVStore
  263. genDoc, privVals := factory.RandGenesisDoc(cfg, n, false, 30)
  264. states := make([]*State, n)
  265. logger := consensusLogger()
  266. for i := 0; i < n; i++ {
  267. stateDB := dbm.NewMemDB() // each state needs its own db
  268. stateStore := sm.NewStore(stateDB)
  269. state, err := sm.MakeGenesisState(genDoc)
  270. require.NoError(t, err)
  271. thisConfig, err := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
  272. require.NoError(t, err)
  273. defer os.RemoveAll(thisConfig.RootDir)
  274. ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal
  275. app := appFunc()
  276. vals := types.TM2PB.ValidatorUpdates(state.Validators)
  277. app.InitChain(abci.RequestInitChain{Validators: vals})
  278. pv := privVals[i]
  279. blockDB := dbm.NewMemDB()
  280. blockStore := store.NewBlockStore(blockDB)
  281. // one for mempool, one for consensus
  282. mtx := new(tmsync.Mutex)
  283. proxyAppConnMem := abciclient.NewLocalClient(mtx, app)
  284. proxyAppConnCon := abciclient.NewLocalClient(mtx, app)
  285. mempool := mempool.NewTxMempool(
  286. log.TestingLogger().With("module", "mempool"),
  287. thisConfig.Mempool,
  288. proxyAppConnMem,
  289. 0,
  290. )
  291. if thisConfig.Consensus.WaitForTxs() {
  292. mempool.EnableTxsAvailable()
  293. }
  294. // mock the evidence pool
  295. // everyone includes evidence of another double signing
  296. vIdx := (i + 1) % n
  297. ev := types.NewMockDuplicateVoteEvidenceWithValidator(1, defaultTestTime, privVals[vIdx], cfg.ChainID())
  298. evpool := &statemocks.EvidencePool{}
  299. evpool.On("CheckEvidence", mock.AnythingOfType("types.EvidenceList")).Return(nil)
  300. evpool.On("PendingEvidence", mock.AnythingOfType("int64")).Return([]types.Evidence{
  301. ev}, int64(len(ev.Bytes())))
  302. evpool.On("Update", mock.AnythingOfType("state.State"), mock.AnythingOfType("types.EvidenceList")).Return()
  303. evpool2 := sm.EmptyEvidencePool{}
  304. blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyAppConnCon, mempool, evpool, blockStore)
  305. cs := NewState(thisConfig.Consensus, state, blockExec, blockStore, mempool, evpool2)
  306. cs.SetLogger(log.TestingLogger().With("module", "consensus"))
  307. cs.SetPrivValidator(pv)
  308. eventBus := types.NewEventBus()
  309. eventBus.SetLogger(log.TestingLogger().With("module", "events"))
  310. err = eventBus.Start()
  311. require.NoError(t, err)
  312. cs.SetEventBus(eventBus)
  313. cs.SetTimeoutTicker(tickerFunc())
  314. cs.SetLogger(logger.With("validator", i, "module", "consensus"))
  315. states[i] = cs
  316. }
  317. rts := setup(t, n, states, 100) // buffer must be large enough to not deadlock
  318. for _, reactor := range rts.reactors {
  319. state := reactor.state.GetState()
  320. reactor.SwitchToConsensus(state, false)
  321. }
  322. var wg sync.WaitGroup
  323. for _, sub := range rts.subs {
  324. wg.Add(1)
  325. // We expect for each validator that is the proposer to propose one piece of
  326. // evidence.
  327. go func(s types.Subscription) {
  328. msg := <-s.Out()
  329. block := msg.Data().(types.EventDataNewBlock).Block
  330. require.Len(t, block.Evidence.Evidence, 1)
  331. wg.Done()
  332. }(sub)
  333. }
  334. wg.Wait()
  335. }
  336. func TestReactorCreatesBlockWhenEmptyBlocksFalse(t *testing.T) {
  337. cfg := configSetup(t)
  338. n := 4
  339. states, cleanup := randConsensusState(
  340. t,
  341. cfg,
  342. n,
  343. "consensus_reactor_test",
  344. newMockTickerFunc(true),
  345. newKVStore,
  346. func(c *config.Config) {
  347. c.Consensus.CreateEmptyBlocks = false
  348. },
  349. )
  350. t.Cleanup(cleanup)
  351. rts := setup(t, n, states, 100) // buffer must be large enough to not deadlock
  352. for _, reactor := range rts.reactors {
  353. state := reactor.state.GetState()
  354. reactor.SwitchToConsensus(state, false)
  355. }
  356. // send a tx
  357. require.NoError(
  358. t,
  359. assertMempool(states[3].txNotifier).CheckTx(
  360. context.Background(),
  361. []byte{1, 2, 3},
  362. nil,
  363. mempool.TxInfo{},
  364. ),
  365. )
  366. var wg sync.WaitGroup
  367. for _, sub := range rts.subs {
  368. wg.Add(1)
  369. // wait till everyone makes the first new block
  370. go func(s types.Subscription) {
  371. <-s.Out()
  372. wg.Done()
  373. }(sub)
  374. }
  375. wg.Wait()
  376. }
  377. func TestReactorRecordsVotesAndBlockParts(t *testing.T) {
  378. cfg := configSetup(t)
  379. n := 4
  380. states, cleanup := randConsensusState(t,
  381. cfg, n, "consensus_reactor_test",
  382. newMockTickerFunc(true), newKVStore)
  383. t.Cleanup(cleanup)
  384. rts := setup(t, n, states, 100) // buffer must be large enough to not deadlock
  385. for _, reactor := range rts.reactors {
  386. state := reactor.state.GetState()
  387. reactor.SwitchToConsensus(state, false)
  388. }
  389. var wg sync.WaitGroup
  390. for _, sub := range rts.subs {
  391. wg.Add(1)
  392. // wait till everyone makes the first new block
  393. go func(s types.Subscription) {
  394. <-s.Out()
  395. wg.Done()
  396. }(sub)
  397. }
  398. wg.Wait()
  399. // Require at least one node to have sent block parts, but we can't know which
  400. // peer sent it.
  401. require.Eventually(
  402. t,
  403. func() bool {
  404. for _, reactor := range rts.reactors {
  405. for _, ps := range reactor.peers {
  406. if ps.BlockPartsSent() > 0 {
  407. return true
  408. }
  409. }
  410. }
  411. return false
  412. },
  413. time.Second,
  414. 10*time.Millisecond,
  415. "number of block parts sent should've increased",
  416. )
  417. nodeID := rts.network.RandomNode().NodeID
  418. reactor := rts.reactors[nodeID]
  419. peers := rts.network.Peers(nodeID)
  420. ps, ok := reactor.GetPeerState(peers[0].NodeID)
  421. require.True(t, ok)
  422. require.NotNil(t, ps)
  423. require.Greater(t, ps.VotesSent(), 0, "number of votes sent should've increased")
  424. }
  425. func TestReactorVotingPowerChange(t *testing.T) {
  426. cfg := configSetup(t)
  427. n := 4
  428. states, cleanup := randConsensusState(
  429. t,
  430. cfg,
  431. n,
  432. "consensus_voting_power_changes_test",
  433. newMockTickerFunc(true),
  434. newPersistentKVStore,
  435. )
  436. t.Cleanup(cleanup)
  437. rts := setup(t, n, states, 100) // buffer must be large enough to not deadlock
  438. for _, reactor := range rts.reactors {
  439. state := reactor.state.GetState()
  440. reactor.SwitchToConsensus(state, false)
  441. }
  442. // map of active validators
  443. activeVals := make(map[string]struct{})
  444. for i := 0; i < n; i++ {
  445. pubKey, err := states[i].privValidator.GetPubKey(context.Background())
  446. require.NoError(t, err)
  447. addr := pubKey.Address()
  448. activeVals[string(addr)] = struct{}{}
  449. }
  450. var wg sync.WaitGroup
  451. for _, sub := range rts.subs {
  452. wg.Add(1)
  453. // wait till everyone makes the first new block
  454. go func(s types.Subscription) {
  455. <-s.Out()
  456. wg.Done()
  457. }(sub)
  458. }
  459. wg.Wait()
  460. blocksSubs := []types.Subscription{}
  461. for _, sub := range rts.subs {
  462. blocksSubs = append(blocksSubs, sub)
  463. }
  464. val1PubKey, err := states[0].privValidator.GetPubKey(context.Background())
  465. require.NoError(t, err)
  466. val1PubKeyABCI, err := encoding.PubKeyToProto(val1PubKey)
  467. require.NoError(t, err)
  468. updateValidatorTx := kvstore.MakeValSetChangeTx(val1PubKeyABCI, 25)
  469. previousTotalVotingPower := states[0].GetRoundState().LastValidators.TotalVotingPower()
  470. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states, updateValidatorTx)
  471. waitForAndValidateBlockWithTx(t, n, activeVals, blocksSubs, states, updateValidatorTx)
  472. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states)
  473. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states)
  474. require.NotEqualf(
  475. t, previousTotalVotingPower, states[0].GetRoundState().LastValidators.TotalVotingPower(),
  476. "expected voting power to change (before: %d, after: %d)",
  477. previousTotalVotingPower,
  478. states[0].GetRoundState().LastValidators.TotalVotingPower(),
  479. )
  480. updateValidatorTx = kvstore.MakeValSetChangeTx(val1PubKeyABCI, 2)
  481. previousTotalVotingPower = states[0].GetRoundState().LastValidators.TotalVotingPower()
  482. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states, updateValidatorTx)
  483. waitForAndValidateBlockWithTx(t, n, activeVals, blocksSubs, states, updateValidatorTx)
  484. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states)
  485. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states)
  486. require.NotEqualf(
  487. t, states[0].GetRoundState().LastValidators.TotalVotingPower(), previousTotalVotingPower,
  488. "expected voting power to change (before: %d, after: %d)",
  489. previousTotalVotingPower, states[0].GetRoundState().LastValidators.TotalVotingPower(),
  490. )
  491. updateValidatorTx = kvstore.MakeValSetChangeTx(val1PubKeyABCI, 26)
  492. previousTotalVotingPower = states[0].GetRoundState().LastValidators.TotalVotingPower()
  493. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states, updateValidatorTx)
  494. waitForAndValidateBlockWithTx(t, n, activeVals, blocksSubs, states, updateValidatorTx)
  495. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states)
  496. waitForAndValidateBlock(t, n, activeVals, blocksSubs, states)
  497. require.NotEqualf(
  498. t, previousTotalVotingPower, states[0].GetRoundState().LastValidators.TotalVotingPower(),
  499. "expected voting power to change (before: %d, after: %d)",
  500. previousTotalVotingPower,
  501. states[0].GetRoundState().LastValidators.TotalVotingPower(),
  502. )
  503. }
  504. func TestReactorValidatorSetChanges(t *testing.T) {
  505. cfg := configSetup(t)
  506. nPeers := 7
  507. nVals := 4
  508. states, _, _, cleanup := randConsensusNetWithPeers(
  509. cfg,
  510. nVals,
  511. nPeers,
  512. "consensus_val_set_changes_test",
  513. newMockTickerFunc(true),
  514. newPersistentKVStoreWithPath,
  515. )
  516. t.Cleanup(cleanup)
  517. rts := setup(t, nPeers, states, 100) // buffer must be large enough to not deadlock
  518. for _, reactor := range rts.reactors {
  519. state := reactor.state.GetState()
  520. reactor.SwitchToConsensus(state, false)
  521. }
  522. // map of active validators
  523. activeVals := make(map[string]struct{})
  524. for i := 0; i < nVals; i++ {
  525. pubKey, err := states[i].privValidator.GetPubKey(context.Background())
  526. require.NoError(t, err)
  527. activeVals[string(pubKey.Address())] = struct{}{}
  528. }
  529. var wg sync.WaitGroup
  530. for _, sub := range rts.subs {
  531. wg.Add(1)
  532. // wait till everyone makes the first new block
  533. go func(s types.Subscription) {
  534. <-s.Out()
  535. wg.Done()
  536. }(sub)
  537. }
  538. wg.Wait()
  539. newValidatorPubKey1, err := states[nVals].privValidator.GetPubKey(context.Background())
  540. require.NoError(t, err)
  541. valPubKey1ABCI, err := encoding.PubKeyToProto(newValidatorPubKey1)
  542. require.NoError(t, err)
  543. newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower)
  544. blocksSubs := []types.Subscription{}
  545. for _, sub := range rts.subs {
  546. blocksSubs = append(blocksSubs, sub)
  547. }
  548. // wait till everyone makes block 2
  549. // ensure the commit includes all validators
  550. // send newValTx to change vals in block 3
  551. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states, newValidatorTx1)
  552. // wait till everyone makes block 3.
  553. // it includes the commit for block 2, which is by the original validator set
  554. waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, states, newValidatorTx1)
  555. // wait till everyone makes block 4.
  556. // it includes the commit for block 3, which is by the original validator set
  557. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states)
  558. // the commits for block 4 should be with the updated validator set
  559. activeVals[string(newValidatorPubKey1.Address())] = struct{}{}
  560. // wait till everyone makes block 5
  561. // it includes the commit for block 4, which should have the updated validator set
  562. waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, states)
  563. updateValidatorPubKey1, err := states[nVals].privValidator.GetPubKey(context.Background())
  564. require.NoError(t, err)
  565. updatePubKey1ABCI, err := encoding.PubKeyToProto(updateValidatorPubKey1)
  566. require.NoError(t, err)
  567. updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25)
  568. previousTotalVotingPower := states[nVals].GetRoundState().LastValidators.TotalVotingPower()
  569. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states, updateValidatorTx1)
  570. waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, states, updateValidatorTx1)
  571. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states)
  572. waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, states)
  573. require.NotEqualf(
  574. t, states[nVals].GetRoundState().LastValidators.TotalVotingPower(), previousTotalVotingPower,
  575. "expected voting power to change (before: %d, after: %d)",
  576. previousTotalVotingPower, states[nVals].GetRoundState().LastValidators.TotalVotingPower(),
  577. )
  578. newValidatorPubKey2, err := states[nVals+1].privValidator.GetPubKey(context.Background())
  579. require.NoError(t, err)
  580. newVal2ABCI, err := encoding.PubKeyToProto(newValidatorPubKey2)
  581. require.NoError(t, err)
  582. newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower)
  583. newValidatorPubKey3, err := states[nVals+2].privValidator.GetPubKey(context.Background())
  584. require.NoError(t, err)
  585. newVal3ABCI, err := encoding.PubKeyToProto(newValidatorPubKey3)
  586. require.NoError(t, err)
  587. newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower)
  588. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states, newValidatorTx2, newValidatorTx3)
  589. waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, states, newValidatorTx2, newValidatorTx3)
  590. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states)
  591. activeVals[string(newValidatorPubKey2.Address())] = struct{}{}
  592. activeVals[string(newValidatorPubKey3.Address())] = struct{}{}
  593. waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, states)
  594. removeValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, 0)
  595. removeValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, 0)
  596. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states, removeValidatorTx2, removeValidatorTx3)
  597. waitForAndValidateBlockWithTx(t, nPeers, activeVals, blocksSubs, states, removeValidatorTx2, removeValidatorTx3)
  598. waitForAndValidateBlock(t, nPeers, activeVals, blocksSubs, states)
  599. delete(activeVals, string(newValidatorPubKey2.Address()))
  600. delete(activeVals, string(newValidatorPubKey3.Address()))
  601. waitForBlockWithUpdatedValsAndValidateIt(t, nPeers, activeVals, blocksSubs, states)
  602. }