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.

1087 lines
34 KiB

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
5 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
5 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
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
cs: sync WAL more frequently (#3300) As per #3043, this adds a ticker to sync the WAL every 2s while the WAL is running. * Flush WAL every 2s This adds a ticker that flushes the WAL every 2s while the WAL is running. This is related to #3043. * Fix spelling * Increase timeout to 2mins for slower build environments * Make WAL sync interval configurable * Add TODO to replace testChan with more comprehensive testBus * Remove extraneous debug statement * Remove testChan in favour of using system time As per https://github.com/tendermint/tendermint/pull/3300#discussion_r255886586, this removes the `testChan` WAL member and replaces the approach with a system time-oriented one. In this new approach, we keep track of the system time at which each flush and periodic flush successfully occurred. The naming of the various functions is also updated here to be more consistent with "flushing" as opposed to "sync'ing". * Update naming convention and ensure lock for timestamp update * Add Flush method as part of WAL interface Adds a `Flush` method as part of the WAL interface to enforce the idea that we can manually trigger a WAL flush from outside of the WAL. This is employed in the consensus state management to flush the WAL prior to signing votes/proposals, as per https://github.com/tendermint/tendermint/issues/3043#issuecomment-453853630 * Update CHANGELOG_PENDING * Remove mutex approach and replace with DI The dependency injection approach to dealing with testing concerns could allow similar effects to some kind of "testing bus"-based approach. This commit introduces an example of this, where instead of relying on (potentially fragile) timing of things between the code and the test, we inject code into the function under test that can signal the test through a channel. This allows us to avoid the `time.Sleep()`-based approach previously employed. * Update comment on WAL flushing during vote signing Co-Authored-By: thanethomson <connect@thanethomson.com> * Simplify flush interval definition Co-Authored-By: thanethomson <connect@thanethomson.com> * Expand commentary on WAL disk flushing Co-Authored-By: thanethomson <connect@thanethomson.com> * Add broken test to illustrate WAL sync test problem Removes test-related state (dependency injection code) from the WAL data structure and adds test code to illustrate the problem with using `WALGenerateNBlocks` and `wal.SearchForEndHeight` to test periodic sync'ing. * Fix test error messages * Use WAL group buffer size to check for flush A function is added to `libs/autofile/group.go#Group` in order to return the size of the buffered data (i.e. data that has not yet been flushed to disk). The test now checks that, prior to a `time.Sleep`, the group buffer has data in it. After the `time.Sleep` (during which time the periodic flush should have been called), the buffer should be empty. * Remove config root dir removal from #3291 * Add godoc for NewWAL mentioning periodic sync
6 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
cs: sync WAL more frequently (#3300) As per #3043, this adds a ticker to sync the WAL every 2s while the WAL is running. * Flush WAL every 2s This adds a ticker that flushes the WAL every 2s while the WAL is running. This is related to #3043. * Fix spelling * Increase timeout to 2mins for slower build environments * Make WAL sync interval configurable * Add TODO to replace testChan with more comprehensive testBus * Remove extraneous debug statement * Remove testChan in favour of using system time As per https://github.com/tendermint/tendermint/pull/3300#discussion_r255886586, this removes the `testChan` WAL member and replaces the approach with a system time-oriented one. In this new approach, we keep track of the system time at which each flush and periodic flush successfully occurred. The naming of the various functions is also updated here to be more consistent with "flushing" as opposed to "sync'ing". * Update naming convention and ensure lock for timestamp update * Add Flush method as part of WAL interface Adds a `Flush` method as part of the WAL interface to enforce the idea that we can manually trigger a WAL flush from outside of the WAL. This is employed in the consensus state management to flush the WAL prior to signing votes/proposals, as per https://github.com/tendermint/tendermint/issues/3043#issuecomment-453853630 * Update CHANGELOG_PENDING * Remove mutex approach and replace with DI The dependency injection approach to dealing with testing concerns could allow similar effects to some kind of "testing bus"-based approach. This commit introduces an example of this, where instead of relying on (potentially fragile) timing of things between the code and the test, we inject code into the function under test that can signal the test through a channel. This allows us to avoid the `time.Sleep()`-based approach previously employed. * Update comment on WAL flushing during vote signing Co-Authored-By: thanethomson <connect@thanethomson.com> * Simplify flush interval definition Co-Authored-By: thanethomson <connect@thanethomson.com> * Expand commentary on WAL disk flushing Co-Authored-By: thanethomson <connect@thanethomson.com> * Add broken test to illustrate WAL sync test problem Removes test-related state (dependency injection code) from the WAL data structure and adds test code to illustrate the problem with using `WALGenerateNBlocks` and `wal.SearchForEndHeight` to test periodic sync'ing. * Fix test error messages * Use WAL group buffer size to check for flush A function is added to `libs/autofile/group.go#Group` in order to return the size of the buffered data (i.e. data that has not yet been flushed to disk). The test now checks that, prior to a `time.Sleep`, the group buffer has data in it. After the `time.Sleep` (during which time the periodic flush should have been called), the buffer should be empty. * Remove config root dir removal from #3291 * Add godoc for NewWAL mentioning periodic sync
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
5 years ago
cs: sync WAL more frequently (#3300) As per #3043, this adds a ticker to sync the WAL every 2s while the WAL is running. * Flush WAL every 2s This adds a ticker that flushes the WAL every 2s while the WAL is running. This is related to #3043. * Fix spelling * Increase timeout to 2mins for slower build environments * Make WAL sync interval configurable * Add TODO to replace testChan with more comprehensive testBus * Remove extraneous debug statement * Remove testChan in favour of using system time As per https://github.com/tendermint/tendermint/pull/3300#discussion_r255886586, this removes the `testChan` WAL member and replaces the approach with a system time-oriented one. In this new approach, we keep track of the system time at which each flush and periodic flush successfully occurred. The naming of the various functions is also updated here to be more consistent with "flushing" as opposed to "sync'ing". * Update naming convention and ensure lock for timestamp update * Add Flush method as part of WAL interface Adds a `Flush` method as part of the WAL interface to enforce the idea that we can manually trigger a WAL flush from outside of the WAL. This is employed in the consensus state management to flush the WAL prior to signing votes/proposals, as per https://github.com/tendermint/tendermint/issues/3043#issuecomment-453853630 * Update CHANGELOG_PENDING * Remove mutex approach and replace with DI The dependency injection approach to dealing with testing concerns could allow similar effects to some kind of "testing bus"-based approach. This commit introduces an example of this, where instead of relying on (potentially fragile) timing of things between the code and the test, we inject code into the function under test that can signal the test through a channel. This allows us to avoid the `time.Sleep()`-based approach previously employed. * Update comment on WAL flushing during vote signing Co-Authored-By: thanethomson <connect@thanethomson.com> * Simplify flush interval definition Co-Authored-By: thanethomson <connect@thanethomson.com> * Expand commentary on WAL disk flushing Co-Authored-By: thanethomson <connect@thanethomson.com> * Add broken test to illustrate WAL sync test problem Removes test-related state (dependency injection code) from the WAL data structure and adds test code to illustrate the problem with using `WALGenerateNBlocks` and `wal.SearchForEndHeight` to test periodic sync'ing. * Fix test error messages * Use WAL group buffer size to check for flush A function is added to `libs/autofile/group.go#Group` in order to return the size of the buffered data (i.e. data that has not yet been flushed to disk). The test now checks that, prior to a `time.Sleep`, the group buffer has data in it. After the `time.Sleep` (during which time the periodic flush should have been called), the buffer should be empty. * Remove config root dir removal from #3291 * Add godoc for NewWAL mentioning periodic sync
6 years ago
cs: sync WAL more frequently (#3300) As per #3043, this adds a ticker to sync the WAL every 2s while the WAL is running. * Flush WAL every 2s This adds a ticker that flushes the WAL every 2s while the WAL is running. This is related to #3043. * Fix spelling * Increase timeout to 2mins for slower build environments * Make WAL sync interval configurable * Add TODO to replace testChan with more comprehensive testBus * Remove extraneous debug statement * Remove testChan in favour of using system time As per https://github.com/tendermint/tendermint/pull/3300#discussion_r255886586, this removes the `testChan` WAL member and replaces the approach with a system time-oriented one. In this new approach, we keep track of the system time at which each flush and periodic flush successfully occurred. The naming of the various functions is also updated here to be more consistent with "flushing" as opposed to "sync'ing". * Update naming convention and ensure lock for timestamp update * Add Flush method as part of WAL interface Adds a `Flush` method as part of the WAL interface to enforce the idea that we can manually trigger a WAL flush from outside of the WAL. This is employed in the consensus state management to flush the WAL prior to signing votes/proposals, as per https://github.com/tendermint/tendermint/issues/3043#issuecomment-453853630 * Update CHANGELOG_PENDING * Remove mutex approach and replace with DI The dependency injection approach to dealing with testing concerns could allow similar effects to some kind of "testing bus"-based approach. This commit introduces an example of this, where instead of relying on (potentially fragile) timing of things between the code and the test, we inject code into the function under test that can signal the test through a channel. This allows us to avoid the `time.Sleep()`-based approach previously employed. * Update comment on WAL flushing during vote signing Co-Authored-By: thanethomson <connect@thanethomson.com> * Simplify flush interval definition Co-Authored-By: thanethomson <connect@thanethomson.com> * Expand commentary on WAL disk flushing Co-Authored-By: thanethomson <connect@thanethomson.com> * Add broken test to illustrate WAL sync test problem Removes test-related state (dependency injection code) from the WAL data structure and adds test code to illustrate the problem with using `WALGenerateNBlocks` and `wal.SearchForEndHeight` to test periodic sync'ing. * Fix test error messages * Use WAL group buffer size to check for flush A function is added to `libs/autofile/group.go#Group` in order to return the size of the buffered data (i.e. data that has not yet been flushed to disk). The test now checks that, prior to a `time.Sleep`, the group buffer has data in it. After the `time.Sleep` (during which time the periodic flush should have been called), the buffer should be empty. * Remove config root dir removal from #3291 * Add godoc for NewWAL mentioning periodic sync
6 years ago
cs: sync WAL more frequently (#3300) As per #3043, this adds a ticker to sync the WAL every 2s while the WAL is running. * Flush WAL every 2s This adds a ticker that flushes the WAL every 2s while the WAL is running. This is related to #3043. * Fix spelling * Increase timeout to 2mins for slower build environments * Make WAL sync interval configurable * Add TODO to replace testChan with more comprehensive testBus * Remove extraneous debug statement * Remove testChan in favour of using system time As per https://github.com/tendermint/tendermint/pull/3300#discussion_r255886586, this removes the `testChan` WAL member and replaces the approach with a system time-oriented one. In this new approach, we keep track of the system time at which each flush and periodic flush successfully occurred. The naming of the various functions is also updated here to be more consistent with "flushing" as opposed to "sync'ing". * Update naming convention and ensure lock for timestamp update * Add Flush method as part of WAL interface Adds a `Flush` method as part of the WAL interface to enforce the idea that we can manually trigger a WAL flush from outside of the WAL. This is employed in the consensus state management to flush the WAL prior to signing votes/proposals, as per https://github.com/tendermint/tendermint/issues/3043#issuecomment-453853630 * Update CHANGELOG_PENDING * Remove mutex approach and replace with DI The dependency injection approach to dealing with testing concerns could allow similar effects to some kind of "testing bus"-based approach. This commit introduces an example of this, where instead of relying on (potentially fragile) timing of things between the code and the test, we inject code into the function under test that can signal the test through a channel. This allows us to avoid the `time.Sleep()`-based approach previously employed. * Update comment on WAL flushing during vote signing Co-Authored-By: thanethomson <connect@thanethomson.com> * Simplify flush interval definition Co-Authored-By: thanethomson <connect@thanethomson.com> * Expand commentary on WAL disk flushing Co-Authored-By: thanethomson <connect@thanethomson.com> * Add broken test to illustrate WAL sync test problem Removes test-related state (dependency injection code) from the WAL data structure and adds test code to illustrate the problem with using `WALGenerateNBlocks` and `wal.SearchForEndHeight` to test periodic sync'ing. * Fix test error messages * Use WAL group buffer size to check for flush A function is added to `libs/autofile/group.go#Group` in order to return the size of the buffered data (i.e. data that has not yet been flushed to disk). The test now checks that, prior to a `time.Sleep`, the group buffer has data in it. After the `time.Sleep` (during which time the periodic flush should have been called), the buffer should be empty. * Remove config root dir removal from #3291 * Add godoc for NewWAL mentioning periodic sync
6 years ago
cs: sync WAL more frequently (#3300) As per #3043, this adds a ticker to sync the WAL every 2s while the WAL is running. * Flush WAL every 2s This adds a ticker that flushes the WAL every 2s while the WAL is running. This is related to #3043. * Fix spelling * Increase timeout to 2mins for slower build environments * Make WAL sync interval configurable * Add TODO to replace testChan with more comprehensive testBus * Remove extraneous debug statement * Remove testChan in favour of using system time As per https://github.com/tendermint/tendermint/pull/3300#discussion_r255886586, this removes the `testChan` WAL member and replaces the approach with a system time-oriented one. In this new approach, we keep track of the system time at which each flush and periodic flush successfully occurred. The naming of the various functions is also updated here to be more consistent with "flushing" as opposed to "sync'ing". * Update naming convention and ensure lock for timestamp update * Add Flush method as part of WAL interface Adds a `Flush` method as part of the WAL interface to enforce the idea that we can manually trigger a WAL flush from outside of the WAL. This is employed in the consensus state management to flush the WAL prior to signing votes/proposals, as per https://github.com/tendermint/tendermint/issues/3043#issuecomment-453853630 * Update CHANGELOG_PENDING * Remove mutex approach and replace with DI The dependency injection approach to dealing with testing concerns could allow similar effects to some kind of "testing bus"-based approach. This commit introduces an example of this, where instead of relying on (potentially fragile) timing of things between the code and the test, we inject code into the function under test that can signal the test through a channel. This allows us to avoid the `time.Sleep()`-based approach previously employed. * Update comment on WAL flushing during vote signing Co-Authored-By: thanethomson <connect@thanethomson.com> * Simplify flush interval definition Co-Authored-By: thanethomson <connect@thanethomson.com> * Expand commentary on WAL disk flushing Co-Authored-By: thanethomson <connect@thanethomson.com> * Add broken test to illustrate WAL sync test problem Removes test-related state (dependency injection code) from the WAL data structure and adds test code to illustrate the problem with using `WALGenerateNBlocks` and `wal.SearchForEndHeight` to test periodic sync'ing. * Fix test error messages * Use WAL group buffer size to check for flush A function is added to `libs/autofile/group.go#Group` in order to return the size of the buffered data (i.e. data that has not yet been flushed to disk). The test now checks that, prior to a `time.Sleep`, the group buffer has data in it. After the `time.Sleep` (during which time the periodic flush should have been called), the buffer should be empty. * Remove config root dir removal from #3291 * Add godoc for NewWAL mentioning periodic sync
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
5 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 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
5 years ago
  1. package consensus
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "runtime"
  11. "testing"
  12. "time"
  13. "github.com/stretchr/testify/assert"
  14. "github.com/stretchr/testify/require"
  15. "sort"
  16. "github.com/tendermint/tendermint/abci/example/kvstore"
  17. abci "github.com/tendermint/tendermint/abci/types"
  18. cfg "github.com/tendermint/tendermint/config"
  19. "github.com/tendermint/tendermint/crypto"
  20. cmn "github.com/tendermint/tendermint/libs/common"
  21. "github.com/tendermint/tendermint/libs/log"
  22. "github.com/tendermint/tendermint/mock"
  23. "github.com/tendermint/tendermint/privval"
  24. "github.com/tendermint/tendermint/proxy"
  25. sm "github.com/tendermint/tendermint/state"
  26. "github.com/tendermint/tendermint/types"
  27. "github.com/tendermint/tendermint/version"
  28. dbm "github.com/tendermint/tm-db"
  29. )
  30. func TestMain(m *testing.M) {
  31. config = ResetConfig("consensus_reactor_test")
  32. consensusReplayConfig = ResetConfig("consensus_replay_test")
  33. configStateTest := ResetConfig("consensus_state_test")
  34. configMempoolTest := ResetConfig("consensus_mempool_test")
  35. configByzantineTest := ResetConfig("consensus_byzantine_test")
  36. code := m.Run()
  37. os.RemoveAll(config.RootDir)
  38. os.RemoveAll(consensusReplayConfig.RootDir)
  39. os.RemoveAll(configStateTest.RootDir)
  40. os.RemoveAll(configMempoolTest.RootDir)
  41. os.RemoveAll(configByzantineTest.RootDir)
  42. os.Exit(code)
  43. }
  44. // These tests ensure we can always recover from failure at any part of the consensus process.
  45. // There are two general failure scenarios: failure during consensus, and failure while applying the block.
  46. // Only the latter interacts with the app and store,
  47. // but the former has to deal with restrictions on re-use of priv_validator keys.
  48. // The `WAL Tests` are for failures during the consensus;
  49. // the `Handshake Tests` are for failures in applying the block.
  50. // With the help of the WAL, we can recover from it all!
  51. //------------------------------------------------------------------------------------------
  52. // WAL Tests
  53. // TODO: It would be better to verify explicitly which states we can recover from without the wal
  54. // and which ones we need the wal for - then we'd also be able to only flush the
  55. // wal writer when we need to, instead of with every message.
  56. func startNewConsensusStateAndWaitForBlock(t *testing.T, consensusReplayConfig *cfg.Config,
  57. lastBlockHeight int64, blockDB dbm.DB, stateDB dbm.DB) {
  58. logger := log.TestingLogger()
  59. state, _ := sm.LoadStateFromDBOrGenesisFile(stateDB, consensusReplayConfig.GenesisFile())
  60. privValidator := loadPrivValidator(consensusReplayConfig)
  61. cs := newConsensusStateWithConfigAndBlockStore(consensusReplayConfig, state, privValidator, kvstore.NewKVStoreApplication(), blockDB)
  62. cs.SetLogger(logger)
  63. bytes, _ := ioutil.ReadFile(cs.config.WalFile())
  64. t.Logf("====== WAL: \n\r%X\n", bytes)
  65. err := cs.Start()
  66. require.NoError(t, err)
  67. defer cs.Stop()
  68. // This is just a signal that we haven't halted; its not something contained
  69. // in the WAL itself. Assuming the consensus state is running, replay of any
  70. // WAL, including the empty one, should eventually be followed by a new
  71. // block, or else something is wrong.
  72. newBlockSub, err := cs.eventBus.Subscribe(context.Background(), testSubscriber, types.EventQueryNewBlock)
  73. require.NoError(t, err)
  74. select {
  75. case <-newBlockSub.Out():
  76. case <-newBlockSub.Cancelled():
  77. t.Fatal("newBlockSub was cancelled")
  78. case <-time.After(120 * time.Second):
  79. t.Fatal("Timed out waiting for new block (see trace above)")
  80. }
  81. }
  82. func sendTxs(ctx context.Context, cs *ConsensusState) {
  83. for i := 0; i < 256; i++ {
  84. select {
  85. case <-ctx.Done():
  86. return
  87. default:
  88. tx := []byte{byte(i)}
  89. assertMempool(cs.txNotifier).CheckTx(tx, nil)
  90. i++
  91. }
  92. }
  93. }
  94. // TestWALCrash uses crashing WAL to test we can recover from any WAL failure.
  95. func TestWALCrash(t *testing.T) {
  96. testCases := []struct {
  97. name string
  98. initFn func(dbm.DB, *ConsensusState, context.Context)
  99. heightToStop int64
  100. }{
  101. {"empty block",
  102. func(stateDB dbm.DB, cs *ConsensusState, ctx context.Context) {},
  103. 1},
  104. {"many non-empty blocks",
  105. func(stateDB dbm.DB, cs *ConsensusState, ctx context.Context) {
  106. go sendTxs(ctx, cs)
  107. },
  108. 3},
  109. }
  110. for i, tc := range testCases {
  111. tc := tc
  112. consensusReplayConfig := ResetConfig(fmt.Sprintf("%s_%d", t.Name(), i))
  113. t.Run(tc.name, func(t *testing.T) {
  114. crashWALandCheckLiveness(t, consensusReplayConfig, tc.initFn, tc.heightToStop)
  115. })
  116. }
  117. }
  118. func crashWALandCheckLiveness(t *testing.T, consensusReplayConfig *cfg.Config,
  119. initFn func(dbm.DB, *ConsensusState, context.Context), heightToStop int64) {
  120. walPanicked := make(chan error)
  121. crashingWal := &crashingWAL{panicCh: walPanicked, heightToStop: heightToStop}
  122. i := 1
  123. LOOP:
  124. for {
  125. t.Logf("====== LOOP %d\n", i)
  126. // create consensus state from a clean slate
  127. logger := log.NewNopLogger()
  128. blockDB := dbm.NewMemDB()
  129. stateDB := blockDB
  130. state, _ := sm.MakeGenesisStateFromFile(consensusReplayConfig.GenesisFile())
  131. privValidator := loadPrivValidator(consensusReplayConfig)
  132. cs := newConsensusStateWithConfigAndBlockStore(consensusReplayConfig, state, privValidator, kvstore.NewKVStoreApplication(), blockDB)
  133. cs.SetLogger(logger)
  134. // start sending transactions
  135. ctx, cancel := context.WithCancel(context.Background())
  136. initFn(stateDB, cs, ctx)
  137. // clean up WAL file from the previous iteration
  138. walFile := cs.config.WalFile()
  139. os.Remove(walFile)
  140. // set crashing WAL
  141. csWal, err := cs.OpenWAL(walFile)
  142. require.NoError(t, err)
  143. crashingWal.next = csWal
  144. // reset the message counter
  145. crashingWal.msgIndex = 1
  146. cs.wal = crashingWal
  147. // start consensus state
  148. err = cs.Start()
  149. require.NoError(t, err)
  150. i++
  151. select {
  152. case err := <-walPanicked:
  153. t.Logf("WAL panicked: %v", err)
  154. // make sure we can make blocks after a crash
  155. startNewConsensusStateAndWaitForBlock(t, consensusReplayConfig, cs.Height, blockDB, stateDB)
  156. // stop consensus state and transactions sender (initFn)
  157. cs.Stop()
  158. cancel()
  159. // if we reached the required height, exit
  160. if _, ok := err.(ReachedHeightToStopError); ok {
  161. break LOOP
  162. }
  163. case <-time.After(10 * time.Second):
  164. t.Fatal("WAL did not panic for 10 seconds (check the log)")
  165. }
  166. }
  167. }
  168. // crashingWAL is a WAL which crashes or rather simulates a crash during Save
  169. // (before and after). It remembers a message for which we last panicked
  170. // (lastPanickedForMsgIndex), so we don't panic for it in subsequent iterations.
  171. type crashingWAL struct {
  172. next WAL
  173. panicCh chan error
  174. heightToStop int64
  175. msgIndex int // current message index
  176. lastPanickedForMsgIndex int // last message for which we panicked
  177. }
  178. var _ WAL = &crashingWAL{}
  179. // WALWriteError indicates a WAL crash.
  180. type WALWriteError struct {
  181. msg string
  182. }
  183. func (e WALWriteError) Error() string {
  184. return e.msg
  185. }
  186. // ReachedHeightToStopError indicates we've reached the required consensus
  187. // height and may exit.
  188. type ReachedHeightToStopError struct {
  189. height int64
  190. }
  191. func (e ReachedHeightToStopError) Error() string {
  192. return fmt.Sprintf("reached height to stop %d", e.height)
  193. }
  194. // Write simulate WAL's crashing by sending an error to the panicCh and then
  195. // exiting the cs.receiveRoutine.
  196. func (w *crashingWAL) Write(m WALMessage) {
  197. if endMsg, ok := m.(EndHeightMessage); ok {
  198. if endMsg.Height == w.heightToStop {
  199. w.panicCh <- ReachedHeightToStopError{endMsg.Height}
  200. runtime.Goexit()
  201. } else {
  202. w.next.Write(m)
  203. }
  204. return
  205. }
  206. if w.msgIndex > w.lastPanickedForMsgIndex {
  207. w.lastPanickedForMsgIndex = w.msgIndex
  208. _, file, line, _ := runtime.Caller(1)
  209. w.panicCh <- WALWriteError{fmt.Sprintf("failed to write %T to WAL (fileline: %s:%d)", m, file, line)}
  210. runtime.Goexit()
  211. } else {
  212. w.msgIndex++
  213. w.next.Write(m)
  214. }
  215. }
  216. func (w *crashingWAL) WriteSync(m WALMessage) {
  217. w.Write(m)
  218. }
  219. func (w *crashingWAL) FlushAndSync() error { return w.next.FlushAndSync() }
  220. func (w *crashingWAL) SearchForEndHeight(height int64, options *WALSearchOptions) (rd io.ReadCloser, found bool, err error) {
  221. return w.next.SearchForEndHeight(height, options)
  222. }
  223. func (w *crashingWAL) Start() error { return w.next.Start() }
  224. func (w *crashingWAL) Stop() error { return w.next.Stop() }
  225. func (w *crashingWAL) Wait() { w.next.Wait() }
  226. //------------------------------------------------------------------------------------------
  227. type testSim struct {
  228. GenesisState sm.State
  229. Config *cfg.Config
  230. Chain []*types.Block
  231. Commits []*types.Commit
  232. CleanupFunc cleanupFunc
  233. }
  234. const (
  235. numBlocks = 6
  236. )
  237. var (
  238. mempool = mock.Mempool{}
  239. evpool = sm.MockEvidencePool{}
  240. sim testSim
  241. )
  242. //---------------------------------------
  243. // Test handshake/replay
  244. // 0 - all synced up
  245. // 1 - saved block but app and state are behind
  246. // 2 - save block and committed but state is behind
  247. var modes = []uint{0, 1, 2}
  248. // This is actually not a test, it's for storing validator change tx data for testHandshakeReplay
  249. func TestSimulateValidatorsChange(t *testing.T) {
  250. nPeers := 7
  251. nVals := 4
  252. css, genDoc, config, cleanup := randConsensusNetWithPeers(nVals, nPeers, "replay_test", newMockTickerFunc(true), newPersistentKVStoreWithPath)
  253. sim.Config = config
  254. sim.GenesisState, _ = sm.MakeGenesisState(genDoc)
  255. sim.CleanupFunc = cleanup
  256. partSize := types.BlockPartSizeBytes
  257. newRoundCh := subscribe(css[0].eventBus, types.EventQueryNewRound)
  258. proposalCh := subscribe(css[0].eventBus, types.EventQueryCompleteProposal)
  259. vss := make([]*validatorStub, nPeers)
  260. for i := 0; i < nPeers; i++ {
  261. vss[i] = NewValidatorStub(css[i].privValidator, i)
  262. }
  263. height, round := css[0].Height, css[0].Round
  264. // start the machine
  265. startTestRound(css[0], height, round)
  266. incrementHeight(vss...)
  267. ensureNewRound(newRoundCh, height, 0)
  268. ensureNewProposal(proposalCh, height, round)
  269. rs := css[0].GetRoundState()
  270. signAddVotes(css[0], types.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...)
  271. ensureNewRound(newRoundCh, height+1, 0)
  272. //height 2
  273. height++
  274. incrementHeight(vss...)
  275. newValidatorPubKey1 := css[nVals].privValidator.GetPubKey()
  276. valPubKey1ABCI := types.TM2PB.PubKey(newValidatorPubKey1)
  277. newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower)
  278. err := assertMempool(css[0].txNotifier).CheckTx(newValidatorTx1, nil)
  279. assert.Nil(t, err)
  280. propBlock, _ := css[0].createProposalBlock() //changeProposer(t, cs1, vs2)
  281. propBlockParts := propBlock.MakePartSet(partSize)
  282. blockID := types.BlockID{Hash: propBlock.Hash(), PartsHeader: propBlockParts.Header()}
  283. proposal := types.NewProposal(vss[1].Height, round, -1, blockID)
  284. if err := vss[1].SignProposal(config.ChainID(), proposal); err != nil {
  285. t.Fatal("failed to sign bad proposal", err)
  286. }
  287. // set the proposal block
  288. if err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil {
  289. t.Fatal(err)
  290. }
  291. ensureNewProposal(proposalCh, height, round)
  292. rs = css[0].GetRoundState()
  293. signAddVotes(css[0], types.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...)
  294. ensureNewRound(newRoundCh, height+1, 0)
  295. //height 3
  296. height++
  297. incrementHeight(vss...)
  298. updateValidatorPubKey1 := css[nVals].privValidator.GetPubKey()
  299. updatePubKey1ABCI := types.TM2PB.PubKey(updateValidatorPubKey1)
  300. updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25)
  301. err = assertMempool(css[0].txNotifier).CheckTx(updateValidatorTx1, nil)
  302. assert.Nil(t, err)
  303. propBlock, _ = css[0].createProposalBlock() //changeProposer(t, cs1, vs2)
  304. propBlockParts = propBlock.MakePartSet(partSize)
  305. blockID = types.BlockID{Hash: propBlock.Hash(), PartsHeader: propBlockParts.Header()}
  306. proposal = types.NewProposal(vss[2].Height, round, -1, blockID)
  307. if err := vss[2].SignProposal(config.ChainID(), proposal); err != nil {
  308. t.Fatal("failed to sign bad proposal", err)
  309. }
  310. // set the proposal block
  311. if err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil {
  312. t.Fatal(err)
  313. }
  314. ensureNewProposal(proposalCh, height, round)
  315. rs = css[0].GetRoundState()
  316. signAddVotes(css[0], types.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...)
  317. ensureNewRound(newRoundCh, height+1, 0)
  318. //height 4
  319. height++
  320. incrementHeight(vss...)
  321. newValidatorPubKey2 := css[nVals+1].privValidator.GetPubKey()
  322. newVal2ABCI := types.TM2PB.PubKey(newValidatorPubKey2)
  323. newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower)
  324. err = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx2, nil)
  325. assert.Nil(t, err)
  326. newValidatorPubKey3 := css[nVals+2].privValidator.GetPubKey()
  327. newVal3ABCI := types.TM2PB.PubKey(newValidatorPubKey3)
  328. newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower)
  329. err = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx3, nil)
  330. assert.Nil(t, err)
  331. propBlock, _ = css[0].createProposalBlock() //changeProposer(t, cs1, vs2)
  332. propBlockParts = propBlock.MakePartSet(partSize)
  333. blockID = types.BlockID{Hash: propBlock.Hash(), PartsHeader: propBlockParts.Header()}
  334. newVss := make([]*validatorStub, nVals+1)
  335. copy(newVss, vss[:nVals+1])
  336. sort.Sort(ValidatorStubsByAddress(newVss))
  337. selfIndex := 0
  338. for i, vs := range newVss {
  339. if vs.GetPubKey().Equals(css[0].privValidator.GetPubKey()) {
  340. selfIndex = i
  341. break
  342. }
  343. }
  344. proposal = types.NewProposal(vss[3].Height, round, -1, blockID)
  345. if err := vss[3].SignProposal(config.ChainID(), proposal); err != nil {
  346. t.Fatal("failed to sign bad proposal", err)
  347. }
  348. // set the proposal block
  349. if err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil {
  350. t.Fatal(err)
  351. }
  352. ensureNewProposal(proposalCh, height, round)
  353. removeValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, 0)
  354. err = assertMempool(css[0].txNotifier).CheckTx(removeValidatorTx2, nil)
  355. assert.Nil(t, err)
  356. rs = css[0].GetRoundState()
  357. for i := 0; i < nVals+1; i++ {
  358. if i == selfIndex {
  359. continue
  360. }
  361. signAddVotes(css[0], types.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), newVss[i])
  362. }
  363. ensureNewRound(newRoundCh, height+1, 0)
  364. //height 5
  365. height++
  366. incrementHeight(vss...)
  367. ensureNewProposal(proposalCh, height, round)
  368. rs = css[0].GetRoundState()
  369. for i := 0; i < nVals+1; i++ {
  370. if i == selfIndex {
  371. continue
  372. }
  373. signAddVotes(css[0], types.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), newVss[i])
  374. }
  375. ensureNewRound(newRoundCh, height+1, 0)
  376. //height 6
  377. height++
  378. incrementHeight(vss...)
  379. removeValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, 0)
  380. err = assertMempool(css[0].txNotifier).CheckTx(removeValidatorTx3, nil)
  381. assert.Nil(t, err)
  382. propBlock, _ = css[0].createProposalBlock() //changeProposer(t, cs1, vs2)
  383. propBlockParts = propBlock.MakePartSet(partSize)
  384. blockID = types.BlockID{Hash: propBlock.Hash(), PartsHeader: propBlockParts.Header()}
  385. newVss = make([]*validatorStub, nVals+3)
  386. copy(newVss, vss[:nVals+3])
  387. sort.Sort(ValidatorStubsByAddress(newVss))
  388. for i, vs := range newVss {
  389. if vs.GetPubKey().Equals(css[0].privValidator.GetPubKey()) {
  390. selfIndex = i
  391. break
  392. }
  393. }
  394. proposal = types.NewProposal(vss[1].Height, round, -1, blockID)
  395. if err := vss[1].SignProposal(config.ChainID(), proposal); err != nil {
  396. t.Fatal("failed to sign bad proposal", err)
  397. }
  398. // set the proposal block
  399. if err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil {
  400. t.Fatal(err)
  401. }
  402. ensureNewProposal(proposalCh, height, round)
  403. rs = css[0].GetRoundState()
  404. for i := 0; i < nVals+3; i++ {
  405. if i == selfIndex {
  406. continue
  407. }
  408. signAddVotes(css[0], types.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), newVss[i])
  409. }
  410. ensureNewRound(newRoundCh, height+1, 0)
  411. sim.Chain = make([]*types.Block, 0)
  412. sim.Commits = make([]*types.Commit, 0)
  413. for i := 1; i <= numBlocks; i++ {
  414. sim.Chain = append(sim.Chain, css[0].blockStore.LoadBlock(int64(i)))
  415. sim.Commits = append(sim.Commits, css[0].blockStore.LoadBlockCommit(int64(i)))
  416. }
  417. }
  418. // Sync from scratch
  419. func TestHandshakeReplayAll(t *testing.T) {
  420. for _, m := range modes {
  421. testHandshakeReplay(t, config, 0, m, false)
  422. }
  423. for _, m := range modes {
  424. testHandshakeReplay(t, config, 0, m, true)
  425. }
  426. }
  427. // Sync many, not from scratch
  428. func TestHandshakeReplaySome(t *testing.T) {
  429. for _, m := range modes {
  430. testHandshakeReplay(t, config, 1, m, false)
  431. }
  432. for _, m := range modes {
  433. testHandshakeReplay(t, config, 1, m, true)
  434. }
  435. }
  436. // Sync from lagging by one
  437. func TestHandshakeReplayOne(t *testing.T) {
  438. for _, m := range modes {
  439. testHandshakeReplay(t, config, numBlocks-1, m, false)
  440. }
  441. for _, m := range modes {
  442. testHandshakeReplay(t, config, numBlocks-1, m, true)
  443. }
  444. }
  445. // Sync from caught up
  446. func TestHandshakeReplayNone(t *testing.T) {
  447. for _, m := range modes {
  448. testHandshakeReplay(t, config, numBlocks, m, false)
  449. }
  450. for _, m := range modes {
  451. testHandshakeReplay(t, config, numBlocks, m, true)
  452. }
  453. }
  454. // Test mockProxyApp should not panic when app return ABCIResponses with some empty ResponseDeliverTx
  455. func TestMockProxyApp(t *testing.T) {
  456. sim.CleanupFunc() //clean the test env created in TestSimulateValidatorsChange
  457. logger := log.TestingLogger()
  458. var validTxs, invalidTxs = 0, 0
  459. txIndex := 0
  460. assert.NotPanics(t, func() {
  461. abciResWithEmptyDeliverTx := new(sm.ABCIResponses)
  462. abciResWithEmptyDeliverTx.DeliverTx = make([]*abci.ResponseDeliverTx, 0)
  463. abciResWithEmptyDeliverTx.DeliverTx = append(abciResWithEmptyDeliverTx.DeliverTx, &abci.ResponseDeliverTx{})
  464. // called when saveABCIResponses:
  465. bytes := cdc.MustMarshalBinaryBare(abciResWithEmptyDeliverTx)
  466. loadedAbciRes := new(sm.ABCIResponses)
  467. // this also happens sm.LoadABCIResponses
  468. err := cdc.UnmarshalBinaryBare(bytes, loadedAbciRes)
  469. require.NoError(t, err)
  470. mock := newMockProxyApp([]byte("mock_hash"), loadedAbciRes)
  471. abciRes := new(sm.ABCIResponses)
  472. abciRes.DeliverTx = make([]*abci.ResponseDeliverTx, len(loadedAbciRes.DeliverTx))
  473. // Execute transactions and get hash.
  474. proxyCb := func(req *abci.Request, res *abci.Response) {
  475. if r, ok := res.Value.(*abci.Response_DeliverTx); ok {
  476. // TODO: make use of res.Log
  477. // TODO: make use of this info
  478. // Blocks may include invalid txs.
  479. txRes := r.DeliverTx
  480. if txRes.Code == abci.CodeTypeOK {
  481. validTxs++
  482. } else {
  483. logger.Debug("Invalid tx", "code", txRes.Code, "log", txRes.Log)
  484. invalidTxs++
  485. }
  486. abciRes.DeliverTx[txIndex] = txRes
  487. txIndex++
  488. }
  489. }
  490. mock.SetResponseCallback(proxyCb)
  491. someTx := []byte("tx")
  492. mock.DeliverTxAsync(abci.RequestDeliverTx{Tx: someTx})
  493. })
  494. assert.True(t, validTxs == 1)
  495. assert.True(t, invalidTxs == 0)
  496. }
  497. func tempWALWithData(data []byte) string {
  498. walFile, err := ioutil.TempFile("", "wal")
  499. if err != nil {
  500. panic(fmt.Sprintf("failed to create temp WAL file: %v", err))
  501. }
  502. _, err = walFile.Write(data)
  503. if err != nil {
  504. panic(fmt.Sprintf("failed to write to temp WAL file: %v", err))
  505. }
  506. if err := walFile.Close(); err != nil {
  507. panic(fmt.Sprintf("failed to close temp WAL file: %v", err))
  508. }
  509. return walFile.Name()
  510. }
  511. // Make some blocks. Start a fresh app and apply nBlocks blocks. Then restart the app and sync it up with the remaining blocks
  512. func testHandshakeReplay(t *testing.T, config *cfg.Config, nBlocks int, mode uint, testValidatorsChange bool) {
  513. var chain []*types.Block
  514. var commits []*types.Commit
  515. var store *mockBlockStore
  516. var stateDB dbm.DB
  517. var genisisState sm.State
  518. if testValidatorsChange {
  519. testConfig := ResetConfig(fmt.Sprintf("%s_%v_m", t.Name(), mode))
  520. defer os.RemoveAll(testConfig.RootDir)
  521. stateDB = dbm.NewMemDB()
  522. genisisState = sim.GenesisState
  523. config = sim.Config
  524. chain = sim.Chain
  525. commits = sim.Commits
  526. store = newMockBlockStore(config, genisisState.ConsensusParams)
  527. } else { //test single node
  528. testConfig := ResetConfig(fmt.Sprintf("%s_%v_s", t.Name(), mode))
  529. defer os.RemoveAll(testConfig.RootDir)
  530. walBody, err := WALWithNBlocks(t, numBlocks)
  531. require.NoError(t, err)
  532. walFile := tempWALWithData(walBody)
  533. config.Consensus.SetWalFile(walFile)
  534. privVal := privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile())
  535. wal, err := NewWAL(walFile)
  536. require.NoError(t, err)
  537. wal.SetLogger(log.TestingLogger())
  538. err = wal.Start()
  539. require.NoError(t, err)
  540. defer wal.Stop()
  541. chain, commits, err = makeBlockchainFromWAL(wal)
  542. require.NoError(t, err)
  543. stateDB, genisisState, store = stateAndStore(config, privVal.GetPubKey(), kvstore.ProtocolVersion)
  544. }
  545. store.chain = chain
  546. store.commits = commits
  547. state := genisisState.Copy()
  548. // run the chain through state.ApplyBlock to build up the tendermint state
  549. state = buildTMStateFromChain(config, stateDB, state, chain, nBlocks, mode)
  550. latestAppHash := state.AppHash
  551. // make a new client creator
  552. kvstoreApp := kvstore.NewPersistentKVStoreApplication(filepath.Join(config.DBDir(), fmt.Sprintf("replay_test_%d_%d_a", nBlocks, mode)))
  553. clientCreator2 := proxy.NewLocalClientCreator(kvstoreApp)
  554. if nBlocks > 0 {
  555. // run nBlocks against a new client to build up the app state.
  556. // use a throwaway tendermint state
  557. proxyApp := proxy.NewAppConns(clientCreator2)
  558. stateDB1 := dbm.NewMemDB()
  559. sm.SaveState(stateDB1, genisisState)
  560. buildAppStateFromChain(proxyApp, stateDB1, genisisState, chain, nBlocks, mode)
  561. }
  562. // now start the app using the handshake - it should sync
  563. genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())
  564. handshaker := NewHandshaker(stateDB, state, store, genDoc)
  565. proxyApp := proxy.NewAppConns(clientCreator2)
  566. if err := proxyApp.Start(); err != nil {
  567. t.Fatalf("Error starting proxy app connections: %v", err)
  568. }
  569. defer proxyApp.Stop()
  570. if err := handshaker.Handshake(proxyApp); err != nil {
  571. t.Fatalf("Error on abci handshake: %v", err)
  572. }
  573. // get the latest app hash from the app
  574. res, err := proxyApp.Query().InfoSync(abci.RequestInfo{Version: ""})
  575. if err != nil {
  576. t.Fatal(err)
  577. }
  578. // the app hash should be synced up
  579. if !bytes.Equal(latestAppHash, res.LastBlockAppHash) {
  580. t.Fatalf("Expected app hashes to match after handshake/replay. got %X, expected %X", res.LastBlockAppHash, latestAppHash)
  581. }
  582. expectedBlocksToSync := numBlocks - nBlocks
  583. if nBlocks == numBlocks && mode > 0 {
  584. expectedBlocksToSync++
  585. } else if nBlocks > 0 && mode == 1 {
  586. expectedBlocksToSync++
  587. }
  588. if handshaker.NBlocks() != expectedBlocksToSync {
  589. t.Fatalf("Expected handshake to sync %d blocks, got %d", expectedBlocksToSync, handshaker.NBlocks())
  590. }
  591. }
  592. func applyBlock(stateDB dbm.DB, st sm.State, blk *types.Block, proxyApp proxy.AppConns) sm.State {
  593. testPartSize := types.BlockPartSizeBytes
  594. blockExec := sm.NewBlockExecutor(stateDB, log.TestingLogger(), proxyApp.Consensus(), mempool, evpool)
  595. blkID := types.BlockID{Hash: blk.Hash(), PartsHeader: blk.MakePartSet(testPartSize).Header()}
  596. newState, err := blockExec.ApplyBlock(st, blkID, blk)
  597. if err != nil {
  598. panic(err)
  599. }
  600. return newState
  601. }
  602. func buildAppStateFromChain(proxyApp proxy.AppConns, stateDB dbm.DB,
  603. state sm.State, chain []*types.Block, nBlocks int, mode uint) {
  604. // start a new app without handshake, play nBlocks blocks
  605. if err := proxyApp.Start(); err != nil {
  606. panic(err)
  607. }
  608. defer proxyApp.Stop()
  609. state.Version.Consensus.App = kvstore.ProtocolVersion //simulate handshake, receive app version
  610. validators := types.TM2PB.ValidatorUpdates(state.Validators)
  611. if _, err := proxyApp.Consensus().InitChainSync(abci.RequestInitChain{
  612. Validators: validators,
  613. }); err != nil {
  614. panic(err)
  615. }
  616. sm.SaveState(stateDB, state) //save height 1's validatorsInfo
  617. switch mode {
  618. case 0:
  619. for i := 0; i < nBlocks; i++ {
  620. block := chain[i]
  621. state = applyBlock(stateDB, state, block, proxyApp)
  622. }
  623. case 1, 2:
  624. for i := 0; i < nBlocks-1; i++ {
  625. block := chain[i]
  626. state = applyBlock(stateDB, state, block, proxyApp)
  627. }
  628. if mode == 2 {
  629. // update the kvstore height and apphash
  630. // as if we ran commit but not
  631. state = applyBlock(stateDB, state, chain[nBlocks-1], proxyApp)
  632. }
  633. }
  634. }
  635. func buildTMStateFromChain(config *cfg.Config, stateDB dbm.DB, state sm.State, chain []*types.Block, nBlocks int, mode uint) sm.State {
  636. // run the whole chain against this client to build up the tendermint state
  637. clientCreator := proxy.NewLocalClientCreator(kvstore.NewPersistentKVStoreApplication(filepath.Join(config.DBDir(), fmt.Sprintf("replay_test_%d_%d_t", nBlocks, mode))))
  638. proxyApp := proxy.NewAppConns(clientCreator)
  639. if err := proxyApp.Start(); err != nil {
  640. panic(err)
  641. }
  642. defer proxyApp.Stop()
  643. state.Version.Consensus.App = kvstore.ProtocolVersion //simulate handshake, receive app version
  644. validators := types.TM2PB.ValidatorUpdates(state.Validators)
  645. if _, err := proxyApp.Consensus().InitChainSync(abci.RequestInitChain{
  646. Validators: validators,
  647. }); err != nil {
  648. panic(err)
  649. }
  650. sm.SaveState(stateDB, state) //save height 1's validatorsInfo
  651. switch mode {
  652. case 0:
  653. // sync right up
  654. for _, block := range chain {
  655. state = applyBlock(stateDB, state, block, proxyApp)
  656. }
  657. case 1, 2:
  658. // sync up to the penultimate as if we stored the block.
  659. // whether we commit or not depends on the appHash
  660. for _, block := range chain[:len(chain)-1] {
  661. state = applyBlock(stateDB, state, block, proxyApp)
  662. }
  663. // apply the final block to a state copy so we can
  664. // get the right next appHash but keep the state back
  665. applyBlock(stateDB, state, chain[len(chain)-1], proxyApp)
  666. }
  667. return state
  668. }
  669. func TestHandshakePanicsIfAppReturnsWrongAppHash(t *testing.T) {
  670. // 1. Initialize tendermint and commit 3 blocks with the following app hashes:
  671. // - 0x01
  672. // - 0x02
  673. // - 0x03
  674. config := ResetConfig("handshake_test_")
  675. defer os.RemoveAll(config.RootDir)
  676. privVal := privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile())
  677. const appVersion = 0x0
  678. stateDB, state, store := stateAndStore(config, privVal.GetPubKey(), appVersion)
  679. genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())
  680. state.LastValidators = state.Validators.Copy()
  681. // mode = 0 for committing all the blocks
  682. blocks := makeBlocks(3, &state, privVal)
  683. store.chain = blocks
  684. // 2. Tendermint must panic if app returns wrong hash for the first block
  685. // - RANDOM HASH
  686. // - 0x02
  687. // - 0x03
  688. {
  689. app := &badApp{numBlocks: 3, allHashesAreWrong: true}
  690. clientCreator := proxy.NewLocalClientCreator(app)
  691. proxyApp := proxy.NewAppConns(clientCreator)
  692. err := proxyApp.Start()
  693. require.NoError(t, err)
  694. defer proxyApp.Stop()
  695. assert.Panics(t, func() {
  696. h := NewHandshaker(stateDB, state, store, genDoc)
  697. h.Handshake(proxyApp)
  698. })
  699. }
  700. // 3. Tendermint must panic if app returns wrong hash for the last block
  701. // - 0x01
  702. // - 0x02
  703. // - RANDOM HASH
  704. {
  705. app := &badApp{numBlocks: 3, onlyLastHashIsWrong: true}
  706. clientCreator := proxy.NewLocalClientCreator(app)
  707. proxyApp := proxy.NewAppConns(clientCreator)
  708. err := proxyApp.Start()
  709. require.NoError(t, err)
  710. defer proxyApp.Stop()
  711. assert.Panics(t, func() {
  712. h := NewHandshaker(stateDB, state, store, genDoc)
  713. h.Handshake(proxyApp)
  714. })
  715. }
  716. }
  717. func makeBlocks(n int, state *sm.State, privVal types.PrivValidator) []*types.Block {
  718. blocks := make([]*types.Block, 0)
  719. var (
  720. prevBlock *types.Block
  721. prevBlockMeta *types.BlockMeta
  722. )
  723. appHeight := byte(0x01)
  724. for i := 0; i < n; i++ {
  725. height := int64(i + 1)
  726. block, parts := makeBlock(*state, prevBlock, prevBlockMeta, privVal, height)
  727. blocks = append(blocks, block)
  728. prevBlock = block
  729. prevBlockMeta = types.NewBlockMeta(block, parts)
  730. // update state
  731. state.AppHash = []byte{appHeight}
  732. appHeight++
  733. state.LastBlockHeight = height
  734. }
  735. return blocks
  736. }
  737. func makeBlock(state sm.State, lastBlock *types.Block, lastBlockMeta *types.BlockMeta,
  738. privVal types.PrivValidator, height int64) (*types.Block, *types.PartSet) {
  739. lastCommit := types.NewCommit(types.BlockID{}, nil)
  740. if height > 1 {
  741. vote, _ := types.MakeVote(lastBlock.Header.Height, lastBlockMeta.BlockID, state.Validators, privVal, lastBlock.Header.ChainID)
  742. voteCommitSig := vote.CommitSig()
  743. lastCommit = types.NewCommit(lastBlockMeta.BlockID, []*types.CommitSig{voteCommitSig})
  744. }
  745. return state.MakeBlock(height, []types.Tx{}, lastCommit, nil, state.Validators.GetProposer().Address)
  746. }
  747. type badApp struct {
  748. abci.BaseApplication
  749. numBlocks byte
  750. height byte
  751. allHashesAreWrong bool
  752. onlyLastHashIsWrong bool
  753. }
  754. func (app *badApp) Commit() abci.ResponseCommit {
  755. app.height++
  756. if app.onlyLastHashIsWrong {
  757. if app.height == app.numBlocks {
  758. return abci.ResponseCommit{Data: cmn.RandBytes(8)}
  759. }
  760. return abci.ResponseCommit{Data: []byte{app.height}}
  761. } else if app.allHashesAreWrong {
  762. return abci.ResponseCommit{Data: cmn.RandBytes(8)}
  763. }
  764. panic("either allHashesAreWrong or onlyLastHashIsWrong must be set")
  765. }
  766. //--------------------------
  767. // utils for making blocks
  768. func makeBlockchainFromWAL(wal WAL) ([]*types.Block, []*types.Commit, error) {
  769. var height int64
  770. // Search for height marker
  771. gr, found, err := wal.SearchForEndHeight(height, &WALSearchOptions{})
  772. if err != nil {
  773. return nil, nil, err
  774. }
  775. if !found {
  776. return nil, nil, fmt.Errorf("WAL does not contain height %d", height)
  777. }
  778. defer gr.Close() // nolint: errcheck
  779. // log.Notice("Build a blockchain by reading from the WAL")
  780. var (
  781. blocks []*types.Block
  782. commits []*types.Commit
  783. thisBlockParts *types.PartSet
  784. thisBlockCommit *types.Commit
  785. )
  786. dec := NewWALDecoder(gr)
  787. for {
  788. msg, err := dec.Decode()
  789. if err == io.EOF {
  790. break
  791. } else if err != nil {
  792. return nil, nil, err
  793. }
  794. piece := readPieceFromWAL(msg)
  795. if piece == nil {
  796. continue
  797. }
  798. switch p := piece.(type) {
  799. case EndHeightMessage:
  800. // if its not the first one, we have a full block
  801. if thisBlockParts != nil {
  802. var block = new(types.Block)
  803. _, err = cdc.UnmarshalBinaryLengthPrefixedReader(thisBlockParts.GetReader(), block, 0)
  804. if err != nil {
  805. panic(err)
  806. }
  807. if block.Height != height+1 {
  808. panic(fmt.Sprintf("read bad block from wal. got height %d, expected %d", block.Height, height+1))
  809. }
  810. commitHeight := thisBlockCommit.Precommits[0].Height
  811. if commitHeight != height+1 {
  812. panic(fmt.Sprintf("commit doesnt match. got height %d, expected %d", commitHeight, height+1))
  813. }
  814. blocks = append(blocks, block)
  815. commits = append(commits, thisBlockCommit)
  816. height++
  817. }
  818. case *types.PartSetHeader:
  819. thisBlockParts = types.NewPartSetFromHeader(*p)
  820. case *types.Part:
  821. _, err := thisBlockParts.AddPart(p)
  822. if err != nil {
  823. return nil, nil, err
  824. }
  825. case *types.Vote:
  826. if p.Type == types.PrecommitType {
  827. commitSigs := []*types.CommitSig{p.CommitSig()}
  828. thisBlockCommit = types.NewCommit(p.BlockID, commitSigs)
  829. }
  830. }
  831. }
  832. // grab the last block too
  833. var block = new(types.Block)
  834. _, err = cdc.UnmarshalBinaryLengthPrefixedReader(thisBlockParts.GetReader(), block, 0)
  835. if err != nil {
  836. panic(err)
  837. }
  838. if block.Height != height+1 {
  839. panic(fmt.Sprintf("read bad block from wal. got height %d, expected %d", block.Height, height+1))
  840. }
  841. commitHeight := thisBlockCommit.Precommits[0].Height
  842. if commitHeight != height+1 {
  843. panic(fmt.Sprintf("commit doesnt match. got height %d, expected %d", commitHeight, height+1))
  844. }
  845. blocks = append(blocks, block)
  846. commits = append(commits, thisBlockCommit)
  847. return blocks, commits, nil
  848. }
  849. func readPieceFromWAL(msg *TimedWALMessage) interface{} {
  850. // for logging
  851. switch m := msg.Msg.(type) {
  852. case msgInfo:
  853. switch msg := m.Msg.(type) {
  854. case *ProposalMessage:
  855. return &msg.Proposal.BlockID.PartsHeader
  856. case *BlockPartMessage:
  857. return msg.Part
  858. case *VoteMessage:
  859. return msg.Vote
  860. }
  861. case EndHeightMessage:
  862. return m
  863. }
  864. return nil
  865. }
  866. // fresh state and mock store
  867. func stateAndStore(config *cfg.Config, pubKey crypto.PubKey, appVersion version.Protocol) (dbm.DB, sm.State, *mockBlockStore) {
  868. stateDB := dbm.NewMemDB()
  869. state, _ := sm.MakeGenesisStateFromFile(config.GenesisFile())
  870. state.Version.Consensus.App = appVersion
  871. store := newMockBlockStore(config, state.ConsensusParams)
  872. sm.SaveState(stateDB, state)
  873. return stateDB, state, store
  874. }
  875. //----------------------------------
  876. // mock block store
  877. type mockBlockStore struct {
  878. config *cfg.Config
  879. params types.ConsensusParams
  880. chain []*types.Block
  881. commits []*types.Commit
  882. }
  883. // TODO: NewBlockStore(db.NewMemDB) ...
  884. func newMockBlockStore(config *cfg.Config, params types.ConsensusParams) *mockBlockStore {
  885. return &mockBlockStore{config, params, nil, nil}
  886. }
  887. func (bs *mockBlockStore) Height() int64 { return int64(len(bs.chain)) }
  888. func (bs *mockBlockStore) LoadBlock(height int64) *types.Block { return bs.chain[height-1] }
  889. func (bs *mockBlockStore) LoadBlockMeta(height int64) *types.BlockMeta {
  890. block := bs.chain[height-1]
  891. return &types.BlockMeta{
  892. BlockID: types.BlockID{Hash: block.Hash(), PartsHeader: block.MakePartSet(types.BlockPartSizeBytes).Header()},
  893. Header: block.Header,
  894. }
  895. }
  896. func (bs *mockBlockStore) LoadBlockPart(height int64, index int) *types.Part { return nil }
  897. func (bs *mockBlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {
  898. }
  899. func (bs *mockBlockStore) LoadBlockCommit(height int64) *types.Commit {
  900. return bs.commits[height-1]
  901. }
  902. func (bs *mockBlockStore) LoadSeenCommit(height int64) *types.Commit {
  903. return bs.commits[height-1]
  904. }
  905. //---------------------------------------
  906. // Test handshake/init chain
  907. func TestHandshakeUpdatesValidators(t *testing.T) {
  908. val, _ := types.RandValidator(true, 10)
  909. vals := types.NewValidatorSet([]*types.Validator{val})
  910. app := &initChainApp{vals: types.TM2PB.ValidatorUpdates(vals)}
  911. clientCreator := proxy.NewLocalClientCreator(app)
  912. config := ResetConfig("handshake_test_")
  913. defer os.RemoveAll(config.RootDir)
  914. privVal := privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile())
  915. stateDB, state, store := stateAndStore(config, privVal.GetPubKey(), 0x0)
  916. oldValAddr := state.Validators.Validators[0].Address
  917. // now start the app using the handshake - it should sync
  918. genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())
  919. handshaker := NewHandshaker(stateDB, state, store, genDoc)
  920. proxyApp := proxy.NewAppConns(clientCreator)
  921. if err := proxyApp.Start(); err != nil {
  922. t.Fatalf("Error starting proxy app connections: %v", err)
  923. }
  924. defer proxyApp.Stop()
  925. if err := handshaker.Handshake(proxyApp); err != nil {
  926. t.Fatalf("Error on abci handshake: %v", err)
  927. }
  928. // reload the state, check the validator set was updated
  929. state = sm.LoadState(stateDB)
  930. newValAddr := state.Validators.Validators[0].Address
  931. expectValAddr := val.Address
  932. assert.NotEqual(t, oldValAddr, newValAddr)
  933. assert.Equal(t, newValAddr, expectValAddr)
  934. }
  935. // returns the vals on InitChain
  936. type initChainApp struct {
  937. abci.BaseApplication
  938. vals []abci.ValidatorUpdate
  939. }
  940. func (ica *initChainApp) InitChain(req abci.RequestInitChain) abci.ResponseInitChain {
  941. return abci.ResponseInitChain{
  942. Validators: ica.vals,
  943. }
  944. }