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.

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