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.

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