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.

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