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.

853 lines
23 KiB

new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
pubsub 2.0 (#3227) * green pubsub tests :OK: * get rid of clientToQueryMap * Subscribe and SubscribeUnbuffered * start adapting other pkgs to new pubsub * nope * rename MsgAndTags to Message * remove TagMap it does not bring any additional benefits * bring back EventSubscriber * fix test * fix data race in TestStartNextHeightCorrectly ``` Write at 0x00c0001c7418 by goroutine 796: github.com/tendermint/tendermint/consensus.TestStartNextHeightCorrectly() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:1296 +0xad testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Previous read at 0x00c0001c7418 by goroutine 858: github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1631 +0x1366 github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1476 +0x8f github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /go/src/github.com/tendermint/tendermint/consensus/state.go:667 +0xa1e github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:628 +0x794 Goroutine 796 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 testing.runTests.func1() /usr/local/go/src/testing/testing.go:1119 +0xa8 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 testing.runTests() /usr/local/go/src/testing/testing.go:1117 +0x4ee testing.(*M).Run() /usr/local/go/src/testing/testing.go:1034 +0x2ee main.main() _testmain.go:214 +0x332 Goroutine 858 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).startRoutines() /go/src/github.com/tendermint/tendermint/consensus/state.go:334 +0x221 github.com/tendermint/tendermint/consensus.startTestRound() /go/src/github.com/tendermint/tendermint/consensus/common_test.go:122 +0x63 github.com/tendermint/tendermint/consensus.TestStateFullRound1() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:255 +0x397 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ``` * fixes after my own review * fix formatting * wait 100ms before kicking a subscriber out + a test for indexer_service * fixes after my second review * no timeout * add changelog entries * fix merge conflicts * fix typos after Thane's review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * reformat code * rewrite indexer service in the attempt to fix failing test https://github.com/tendermint/tendermint/pull/3227/#issuecomment-462316527 * Revert "rewrite indexer service in the attempt to fix failing test" This reverts commit 0d9107a098230de7138abb1c201877c246e89ed1. * another attempt to fix indexer * fixes after Ethan's review * use unbuffered channel when indexing transactions Refs https://github.com/tendermint/tendermint/pull/3227#discussion_r258786716 * add a comment for EventBus#SubscribeUnbuffered * format code
6 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
6 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
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. // Canceled during cleanup (see below).
  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. i++
  127. }
  128. require.Len(t, rts.reactors, numNodes)
  129. // start the in-memory network and connect all peers with each other
  130. rts.network.Start(ctx, t)
  131. t.Cleanup(func() {
  132. cancel()
  133. leaktest.Check(t)
  134. })
  135. return rts
  136. }
  137. func validateBlock(block *types.Block, activeVals map[string]struct{}) error {
  138. if block.LastCommit.Size() != len(activeVals) {
  139. return fmt.Errorf(
  140. "commit size doesn't match number of active validators. Got %d, expected %d",
  141. block.LastCommit.Size(), len(activeVals),
  142. )
  143. }
  144. for _, commitSig := range block.LastCommit.Signatures {
  145. if _, ok := activeVals[string(commitSig.ValidatorAddress)]; !ok {
  146. return fmt.Errorf("found vote for inactive validator %X", commitSig.ValidatorAddress)
  147. }
  148. }
  149. return nil
  150. }
  151. func waitForAndValidateBlock(
  152. bctx context.Context,
  153. t *testing.T,
  154. n int,
  155. activeVals map[string]struct{},
  156. blocksSubs []eventbus.Subscription,
  157. states []*State,
  158. txs ...[]byte,
  159. ) {
  160. t.Helper()
  161. ctx, cancel := context.WithCancel(bctx)
  162. defer cancel()
  163. fn := func(j int) {
  164. msg, err := blocksSubs[j].Next(ctx)
  165. if !assert.NoError(t, err) {
  166. cancel()
  167. return
  168. }
  169. newBlock := msg.Data().(types.EventDataNewBlock).Block
  170. require.NoError(t, validateBlock(newBlock, activeVals))
  171. for _, tx := range txs {
  172. require.NoError(t, assertMempool(t, states[j].txNotifier).CheckTx(ctx, tx, nil, mempool.TxInfo{}))
  173. }
  174. }
  175. var wg sync.WaitGroup
  176. for i := 0; i < n; i++ {
  177. wg.Add(1)
  178. go func(j int) {
  179. defer wg.Done()
  180. fn(j)
  181. }(i)
  182. }
  183. wg.Wait()
  184. }
  185. func waitForAndValidateBlockWithTx(
  186. bctx context.Context,
  187. t *testing.T,
  188. n int,
  189. activeVals map[string]struct{},
  190. blocksSubs []eventbus.Subscription,
  191. states []*State,
  192. txs ...[]byte,
  193. ) {
  194. t.Helper()
  195. ctx, cancel := context.WithCancel(bctx)
  196. defer cancel()
  197. fn := func(j int) {
  198. ntxs := 0
  199. for {
  200. msg, err := blocksSubs[j].Next(ctx)
  201. if !assert.NoError(t, err) {
  202. cancel()
  203. return
  204. }
  205. newBlock := msg.Data().(types.EventDataNewBlock).Block
  206. require.NoError(t, validateBlock(newBlock, activeVals))
  207. // check that txs match the txs we're waiting for.
  208. // note they could be spread over multiple blocks,
  209. // but they should be in order.
  210. for _, tx := range newBlock.Data.Txs {
  211. require.EqualValues(t, txs[ntxs], tx)
  212. ntxs++
  213. }
  214. if ntxs == len(txs) {
  215. break
  216. }
  217. }
  218. }
  219. var wg sync.WaitGroup
  220. for i := 0; i < n; i++ {
  221. wg.Add(1)
  222. go func(j int) {
  223. defer wg.Done()
  224. fn(j)
  225. }(i)
  226. }
  227. wg.Wait()
  228. }
  229. func waitForBlockWithUpdatedValsAndValidateIt(
  230. bctx context.Context,
  231. t *testing.T,
  232. n int,
  233. updatedVals map[string]struct{},
  234. blocksSubs []eventbus.Subscription,
  235. css []*State,
  236. ) {
  237. t.Helper()
  238. ctx, cancel := context.WithCancel(bctx)
  239. defer cancel()
  240. fn := func(j int) {
  241. var newBlock *types.Block
  242. for {
  243. msg, err := blocksSubs[j].Next(ctx)
  244. if !assert.NoError(t, err) {
  245. cancel()
  246. return
  247. }
  248. newBlock = msg.Data().(types.EventDataNewBlock).Block
  249. if newBlock.LastCommit.Size() == len(updatedVals) {
  250. break
  251. }
  252. }
  253. require.NoError(t, validateBlock(newBlock, updatedVals))
  254. }
  255. var wg sync.WaitGroup
  256. for i := 0; i < n; i++ {
  257. wg.Add(1)
  258. go func(j int) {
  259. defer wg.Done()
  260. fn(j)
  261. }(i)
  262. }
  263. wg.Wait()
  264. }
  265. func ensureBlockSyncStatus(t *testing.T, msg tmpubsub.Message, complete bool, height int64) {
  266. t.Helper()
  267. status, ok := msg.Data().(types.EventDataBlockSyncStatus)
  268. require.True(t, ok)
  269. require.Equal(t, complete, status.Complete)
  270. require.Equal(t, height, status.Height)
  271. }
  272. func TestReactorBasic(t *testing.T) {
  273. ctx, cancel := context.WithCancel(context.Background())
  274. defer cancel()
  275. cfg := configSetup(t)
  276. n := 4
  277. states, cleanup := randConsensusState(ctx, t,
  278. cfg, n, "consensus_reactor_test",
  279. newMockTickerFunc(true), newKVStore)
  280. t.Cleanup(cleanup)
  281. rts := setup(ctx, t, n, states, 100) // buffer must be large enough to not deadlock
  282. for _, reactor := range rts.reactors {
  283. state := reactor.state.GetState()
  284. reactor.SwitchToConsensus(ctx, state, false)
  285. }
  286. var wg sync.WaitGroup
  287. for _, sub := range rts.subs {
  288. wg.Add(1)
  289. // wait till everyone makes the first new block
  290. go func(s eventbus.Subscription) {
  291. defer wg.Done()
  292. _, err := s.Next(ctx)
  293. if !assert.NoError(t, err) {
  294. cancel()
  295. }
  296. }(sub)
  297. }
  298. wg.Wait()
  299. for _, sub := range rts.blocksyncSubs {
  300. wg.Add(1)
  301. // wait till everyone makes the consensus switch
  302. go func(s eventbus.Subscription) {
  303. defer wg.Done()
  304. msg, err := s.Next(ctx)
  305. if !assert.NoError(t, err) {
  306. cancel()
  307. return
  308. }
  309. ensureBlockSyncStatus(t, msg, true, 0)
  310. }(sub)
  311. }
  312. wg.Wait()
  313. }
  314. func TestReactorWithEvidence(t *testing.T) {
  315. ctx, cancel := context.WithCancel(context.Background())
  316. defer cancel()
  317. cfg := configSetup(t)
  318. n := 4
  319. testName := "consensus_reactor_test"
  320. tickerFunc := newMockTickerFunc(true)
  321. appFunc := newKVStore
  322. genDoc, privVals := factory.RandGenesisDoc(ctx, t, cfg, n, false, 30)
  323. states := make([]*State, n)
  324. logger := consensusLogger()
  325. for i := 0; i < n; i++ {
  326. stateDB := dbm.NewMemDB() // each state needs its own db
  327. stateStore := sm.NewStore(stateDB)
  328. state, err := sm.MakeGenesisState(genDoc)
  329. require.NoError(t, err)
  330. thisConfig, err := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
  331. require.NoError(t, err)
  332. defer os.RemoveAll(thisConfig.RootDir)
  333. ensureDir(t, path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal
  334. app := appFunc(t, logger)
  335. vals := types.TM2PB.ValidatorUpdates(state.Validators)
  336. app.InitChain(abci.RequestInitChain{Validators: vals})
  337. pv := privVals[i]
  338. blockDB := dbm.NewMemDB()
  339. blockStore := store.NewBlockStore(blockDB)
  340. // one for mempool, one for consensus
  341. mtx := new(sync.Mutex)
  342. proxyAppConnMem := abciclient.NewLocalClient(logger, mtx, app)
  343. proxyAppConnCon := abciclient.NewLocalClient(logger, mtx, app)
  344. mempool := mempool.NewTxMempool(
  345. log.TestingLogger().With("module", "mempool"),
  346. thisConfig.Mempool,
  347. proxyAppConnMem,
  348. 0,
  349. )
  350. if thisConfig.Consensus.WaitForTxs() {
  351. mempool.EnableTxsAvailable()
  352. }
  353. // mock the evidence pool
  354. // everyone includes evidence of another double signing
  355. vIdx := (i + 1) % n
  356. ev, err := types.NewMockDuplicateVoteEvidenceWithValidator(ctx, 1, defaultTestTime, privVals[vIdx], cfg.ChainID())
  357. require.NoError(t, err)
  358. evpool := &statemocks.EvidencePool{}
  359. evpool.On("CheckEvidence", mock.AnythingOfType("types.EvidenceList")).Return(nil)
  360. evpool.On("PendingEvidence", mock.AnythingOfType("int64")).Return([]types.Evidence{
  361. ev}, int64(len(ev.Bytes())))
  362. evpool.On("Update", mock.AnythingOfType("state.State"), mock.AnythingOfType("types.EvidenceList")).Return()
  363. evpool2 := sm.EmptyEvidencePool{}
  364. blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyAppConnCon, mempool, evpool, blockStore)
  365. cs := NewState(ctx, logger.With("validator", i, "module", "consensus"),
  366. thisConfig.Consensus, state, blockExec, blockStore, mempool, evpool2)
  367. cs.SetPrivValidator(ctx, pv)
  368. eventBus := eventbus.NewDefault(log.TestingLogger().With("module", "events"))
  369. require.NoError(t, eventBus.Start(ctx))
  370. cs.SetEventBus(eventBus)
  371. cs.SetTimeoutTicker(tickerFunc())
  372. states[i] = cs
  373. }
  374. rts := setup(ctx, t, n, states, 100) // buffer must be large enough to not deadlock
  375. for _, reactor := range rts.reactors {
  376. state := reactor.state.GetState()
  377. reactor.SwitchToConsensus(ctx, state, false)
  378. }
  379. var wg sync.WaitGroup
  380. for _, sub := range rts.subs {
  381. wg.Add(1)
  382. // We expect for each validator that is the proposer to propose one piece of
  383. // evidence.
  384. go func(s eventbus.Subscription) {
  385. defer wg.Done()
  386. msg, err := s.Next(ctx)
  387. if !assert.NoError(t, err) {
  388. cancel()
  389. return
  390. }
  391. block := msg.Data().(types.EventDataNewBlock).Block
  392. require.Len(t, block.Evidence.Evidence, 1)
  393. }(sub)
  394. }
  395. wg.Wait()
  396. }
  397. func TestReactorCreatesBlockWhenEmptyBlocksFalse(t *testing.T) {
  398. ctx, cancel := context.WithCancel(context.Background())
  399. defer cancel()
  400. cfg := configSetup(t)
  401. n := 4
  402. states, cleanup := randConsensusState(
  403. ctx,
  404. t,
  405. cfg,
  406. n,
  407. "consensus_reactor_test",
  408. newMockTickerFunc(true),
  409. newKVStore,
  410. func(c *config.Config) {
  411. c.Consensus.CreateEmptyBlocks = false
  412. },
  413. )
  414. t.Cleanup(cleanup)
  415. rts := setup(ctx, t, n, states, 100) // buffer must be large enough to not deadlock
  416. for _, reactor := range rts.reactors {
  417. state := reactor.state.GetState()
  418. reactor.SwitchToConsensus(ctx, state, false)
  419. }
  420. // send a tx
  421. require.NoError(
  422. t,
  423. assertMempool(t, states[3].txNotifier).CheckTx(
  424. ctx,
  425. []byte{1, 2, 3},
  426. nil,
  427. mempool.TxInfo{},
  428. ),
  429. )
  430. var wg sync.WaitGroup
  431. for _, sub := range rts.subs {
  432. wg.Add(1)
  433. // wait till everyone makes the first new block
  434. go func(s eventbus.Subscription) {
  435. defer wg.Done()
  436. _, err := s.Next(ctx)
  437. if !assert.NoError(t, err) {
  438. cancel()
  439. }
  440. }(sub)
  441. }
  442. wg.Wait()
  443. }
  444. func TestReactorRecordsVotesAndBlockParts(t *testing.T) {
  445. ctx, cancel := context.WithCancel(context.Background())
  446. defer cancel()
  447. cfg := configSetup(t)
  448. n := 4
  449. states, cleanup := randConsensusState(ctx, t,
  450. cfg, n, "consensus_reactor_test",
  451. newMockTickerFunc(true), newKVStore)
  452. t.Cleanup(cleanup)
  453. rts := setup(ctx, t, n, states, 100) // buffer must be large enough to not deadlock
  454. for _, reactor := range rts.reactors {
  455. state := reactor.state.GetState()
  456. reactor.SwitchToConsensus(ctx, state, false)
  457. }
  458. var wg sync.WaitGroup
  459. for _, sub := range rts.subs {
  460. wg.Add(1)
  461. // wait till everyone makes the first new block
  462. go func(s eventbus.Subscription) {
  463. defer wg.Done()
  464. _, err := s.Next(ctx)
  465. if !assert.NoError(t, err) {
  466. cancel()
  467. }
  468. }(sub)
  469. }
  470. wg.Wait()
  471. // Require at least one node to have sent block parts, but we can't know which
  472. // peer sent it.
  473. require.Eventually(
  474. t,
  475. func() bool {
  476. for _, reactor := range rts.reactors {
  477. for _, ps := range reactor.peers {
  478. if ps.BlockPartsSent() > 0 {
  479. return true
  480. }
  481. }
  482. }
  483. return false
  484. },
  485. time.Second,
  486. 10*time.Millisecond,
  487. "number of block parts sent should've increased",
  488. )
  489. nodeID := rts.network.RandomNode().NodeID
  490. reactor := rts.reactors[nodeID]
  491. peers := rts.network.Peers(nodeID)
  492. ps, ok := reactor.GetPeerState(peers[0].NodeID)
  493. require.True(t, ok)
  494. require.NotNil(t, ps)
  495. require.Greater(t, ps.VotesSent(), 0, "number of votes sent should've increased")
  496. }
  497. func TestReactorVotingPowerChange(t *testing.T) {
  498. ctx, cancel := context.WithCancel(context.Background())
  499. defer cancel()
  500. cfg := configSetup(t)
  501. n := 4
  502. states, cleanup := randConsensusState(
  503. ctx,
  504. t,
  505. cfg,
  506. n,
  507. "consensus_voting_power_changes_test",
  508. newMockTickerFunc(true),
  509. newPersistentKVStore,
  510. )
  511. t.Cleanup(cleanup)
  512. rts := setup(ctx, t, n, states, 100) // buffer must be large enough to not deadlock
  513. for _, reactor := range rts.reactors {
  514. state := reactor.state.GetState()
  515. reactor.SwitchToConsensus(ctx, state, false)
  516. }
  517. // map of active validators
  518. activeVals := make(map[string]struct{})
  519. for i := 0; i < n; i++ {
  520. pubKey, err := states[i].privValidator.GetPubKey(ctx)
  521. require.NoError(t, err)
  522. addr := pubKey.Address()
  523. activeVals[string(addr)] = struct{}{}
  524. }
  525. var wg sync.WaitGroup
  526. for _, sub := range rts.subs {
  527. wg.Add(1)
  528. // wait till everyone makes the first new block
  529. go func(s eventbus.Subscription) {
  530. defer wg.Done()
  531. _, err := s.Next(ctx)
  532. if !assert.NoError(t, err) {
  533. cancel()
  534. }
  535. }(sub)
  536. }
  537. wg.Wait()
  538. blocksSubs := []eventbus.Subscription{}
  539. for _, sub := range rts.subs {
  540. blocksSubs = append(blocksSubs, sub)
  541. }
  542. val1PubKey, err := states[0].privValidator.GetPubKey(ctx)
  543. require.NoError(t, err)
  544. val1PubKeyABCI, err := encoding.PubKeyToProto(val1PubKey)
  545. require.NoError(t, err)
  546. updateValidatorTx := kvstore.MakeValSetChangeTx(val1PubKeyABCI, 25)
  547. previousTotalVotingPower := states[0].GetRoundState().LastValidators.TotalVotingPower()
  548. waitForAndValidateBlock(ctx, t, n, activeVals, blocksSubs, states, updateValidatorTx)
  549. waitForAndValidateBlockWithTx(ctx, t, n, activeVals, blocksSubs, states, updateValidatorTx)
  550. waitForAndValidateBlock(ctx, t, n, activeVals, blocksSubs, states)
  551. waitForAndValidateBlock(ctx, t, n, activeVals, blocksSubs, states)
  552. require.NotEqualf(
  553. t, previousTotalVotingPower, states[0].GetRoundState().LastValidators.TotalVotingPower(),
  554. "expected voting power to change (before: %d, after: %d)",
  555. previousTotalVotingPower,
  556. states[0].GetRoundState().LastValidators.TotalVotingPower(),
  557. )
  558. updateValidatorTx = kvstore.MakeValSetChangeTx(val1PubKeyABCI, 2)
  559. previousTotalVotingPower = states[0].GetRoundState().LastValidators.TotalVotingPower()
  560. waitForAndValidateBlock(ctx, t, n, activeVals, blocksSubs, states, updateValidatorTx)
  561. waitForAndValidateBlockWithTx(ctx, t, n, activeVals, blocksSubs, states, updateValidatorTx)
  562. waitForAndValidateBlock(ctx, t, n, activeVals, blocksSubs, states)
  563. waitForAndValidateBlock(ctx, t, n, activeVals, blocksSubs, states)
  564. require.NotEqualf(
  565. t, states[0].GetRoundState().LastValidators.TotalVotingPower(), previousTotalVotingPower,
  566. "expected voting power to change (before: %d, after: %d)",
  567. previousTotalVotingPower, states[0].GetRoundState().LastValidators.TotalVotingPower(),
  568. )
  569. updateValidatorTx = kvstore.MakeValSetChangeTx(val1PubKeyABCI, 26)
  570. previousTotalVotingPower = states[0].GetRoundState().LastValidators.TotalVotingPower()
  571. waitForAndValidateBlock(ctx, t, n, activeVals, blocksSubs, states, updateValidatorTx)
  572. waitForAndValidateBlockWithTx(ctx, t, n, activeVals, blocksSubs, states, updateValidatorTx)
  573. waitForAndValidateBlock(ctx, t, n, activeVals, blocksSubs, states)
  574. waitForAndValidateBlock(ctx, t, n, activeVals, blocksSubs, states)
  575. require.NotEqualf(
  576. t, previousTotalVotingPower, states[0].GetRoundState().LastValidators.TotalVotingPower(),
  577. "expected voting power to change (before: %d, after: %d)",
  578. previousTotalVotingPower,
  579. states[0].GetRoundState().LastValidators.TotalVotingPower(),
  580. )
  581. }
  582. func TestReactorValidatorSetChanges(t *testing.T) {
  583. ctx, cancel := context.WithCancel(context.Background())
  584. defer cancel()
  585. cfg := configSetup(t)
  586. nPeers := 7
  587. nVals := 4
  588. states, _, _, cleanup := randConsensusNetWithPeers(
  589. ctx,
  590. t,
  591. cfg,
  592. nVals,
  593. nPeers,
  594. "consensus_val_set_changes_test",
  595. newMockTickerFunc(true),
  596. newPersistentKVStoreWithPath,
  597. )
  598. t.Cleanup(cleanup)
  599. rts := setup(ctx, t, nPeers, states, 100) // buffer must be large enough to not deadlock
  600. for _, reactor := range rts.reactors {
  601. state := reactor.state.GetState()
  602. reactor.SwitchToConsensus(ctx, state, false)
  603. }
  604. // map of active validators
  605. activeVals := make(map[string]struct{})
  606. for i := 0; i < nVals; i++ {
  607. pubKey, err := states[i].privValidator.GetPubKey(ctx)
  608. require.NoError(t, err)
  609. activeVals[string(pubKey.Address())] = struct{}{}
  610. }
  611. var wg sync.WaitGroup
  612. for _, sub := range rts.subs {
  613. wg.Add(1)
  614. // wait till everyone makes the first new block
  615. go func(s eventbus.Subscription) {
  616. defer wg.Done()
  617. _, err := s.Next(ctx)
  618. if !assert.NoError(t, err) {
  619. cancel()
  620. }
  621. }(sub)
  622. }
  623. wg.Wait()
  624. newValidatorPubKey1, err := states[nVals].privValidator.GetPubKey(ctx)
  625. require.NoError(t, err)
  626. valPubKey1ABCI, err := encoding.PubKeyToProto(newValidatorPubKey1)
  627. require.NoError(t, err)
  628. newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower)
  629. blocksSubs := []eventbus.Subscription{}
  630. for _, sub := range rts.subs {
  631. blocksSubs = append(blocksSubs, sub)
  632. }
  633. // wait till everyone makes block 2
  634. // ensure the commit includes all validators
  635. // send newValTx to change vals in block 3
  636. waitForAndValidateBlock(ctx, t, nPeers, activeVals, blocksSubs, states, newValidatorTx1)
  637. // wait till everyone makes block 3.
  638. // it includes the commit for block 2, which is by the original validator set
  639. waitForAndValidateBlockWithTx(ctx, t, nPeers, activeVals, blocksSubs, states, newValidatorTx1)
  640. // wait till everyone makes block 4.
  641. // it includes the commit for block 3, which is by the original validator set
  642. waitForAndValidateBlock(ctx, t, nPeers, activeVals, blocksSubs, states)
  643. // the commits for block 4 should be with the updated validator set
  644. activeVals[string(newValidatorPubKey1.Address())] = struct{}{}
  645. // wait till everyone makes block 5
  646. // it includes the commit for block 4, which should have the updated validator set
  647. waitForBlockWithUpdatedValsAndValidateIt(ctx, t, nPeers, activeVals, blocksSubs, states)
  648. updateValidatorPubKey1, err := states[nVals].privValidator.GetPubKey(ctx)
  649. require.NoError(t, err)
  650. updatePubKey1ABCI, err := encoding.PubKeyToProto(updateValidatorPubKey1)
  651. require.NoError(t, err)
  652. updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25)
  653. previousTotalVotingPower := states[nVals].GetRoundState().LastValidators.TotalVotingPower()
  654. waitForAndValidateBlock(ctx, t, nPeers, activeVals, blocksSubs, states, updateValidatorTx1)
  655. waitForAndValidateBlockWithTx(ctx, t, nPeers, activeVals, blocksSubs, states, updateValidatorTx1)
  656. waitForAndValidateBlock(ctx, t, nPeers, activeVals, blocksSubs, states)
  657. waitForBlockWithUpdatedValsAndValidateIt(ctx, t, nPeers, activeVals, blocksSubs, states)
  658. require.NotEqualf(
  659. t, states[nVals].GetRoundState().LastValidators.TotalVotingPower(), previousTotalVotingPower,
  660. "expected voting power to change (before: %d, after: %d)",
  661. previousTotalVotingPower, states[nVals].GetRoundState().LastValidators.TotalVotingPower(),
  662. )
  663. newValidatorPubKey2, err := states[nVals+1].privValidator.GetPubKey(ctx)
  664. require.NoError(t, err)
  665. newVal2ABCI, err := encoding.PubKeyToProto(newValidatorPubKey2)
  666. require.NoError(t, err)
  667. newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower)
  668. newValidatorPubKey3, err := states[nVals+2].privValidator.GetPubKey(ctx)
  669. require.NoError(t, err)
  670. newVal3ABCI, err := encoding.PubKeyToProto(newValidatorPubKey3)
  671. require.NoError(t, err)
  672. newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower)
  673. waitForAndValidateBlock(ctx, t, nPeers, activeVals, blocksSubs, states, newValidatorTx2, newValidatorTx3)
  674. waitForAndValidateBlockWithTx(ctx, t, nPeers, activeVals, blocksSubs, states, newValidatorTx2, newValidatorTx3)
  675. waitForAndValidateBlock(ctx, t, nPeers, activeVals, blocksSubs, states)
  676. activeVals[string(newValidatorPubKey2.Address())] = struct{}{}
  677. activeVals[string(newValidatorPubKey3.Address())] = struct{}{}
  678. waitForBlockWithUpdatedValsAndValidateIt(ctx, t, nPeers, activeVals, blocksSubs, states)
  679. removeValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, 0)
  680. removeValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, 0)
  681. waitForAndValidateBlock(ctx, t, nPeers, activeVals, blocksSubs, states, removeValidatorTx2, removeValidatorTx3)
  682. waitForAndValidateBlockWithTx(ctx, t, nPeers, activeVals, blocksSubs, states, removeValidatorTx2, removeValidatorTx3)
  683. waitForAndValidateBlock(ctx, t, nPeers, activeVals, blocksSubs, states)
  684. delete(activeVals, string(newValidatorPubKey2.Address()))
  685. delete(activeVals, string(newValidatorPubKey3.Address()))
  686. waitForBlockWithUpdatedValsAndValidateIt(ctx, t, nPeers, activeVals, blocksSubs, states)
  687. }