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.

1086 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
6 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
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: 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
6 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
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
  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. consensusReplayConfig := ResetConfig(fmt.Sprintf("%s_%d", t.Name(), i))
  112. t.Run(tc.name, func(t *testing.T) {
  113. crashWALandCheckLiveness(t, consensusReplayConfig, tc.initFn, tc.heightToStop)
  114. })
  115. }
  116. }
  117. func crashWALandCheckLiveness(t *testing.T, consensusReplayConfig *cfg.Config,
  118. initFn func(dbm.DB, *ConsensusState, context.Context), heightToStop int64) {
  119. walPanicked := make(chan error)
  120. crashingWal := &crashingWAL{panicCh: walPanicked, heightToStop: heightToStop}
  121. i := 1
  122. LOOP:
  123. for {
  124. t.Logf("====== LOOP %d\n", i)
  125. // create consensus state from a clean slate
  126. logger := log.NewNopLogger()
  127. blockDB := dbm.NewMemDB()
  128. stateDB := blockDB
  129. state, _ := sm.MakeGenesisStateFromFile(consensusReplayConfig.GenesisFile())
  130. privValidator := loadPrivValidator(consensusReplayConfig)
  131. cs := newConsensusStateWithConfigAndBlockStore(consensusReplayConfig, state, privValidator, kvstore.NewKVStoreApplication(), blockDB)
  132. cs.SetLogger(logger)
  133. // start sending transactions
  134. ctx, cancel := context.WithCancel(context.Background())
  135. initFn(stateDB, cs, ctx)
  136. // clean up WAL file from the previous iteration
  137. walFile := cs.config.WalFile()
  138. os.Remove(walFile)
  139. // set crashing WAL
  140. csWal, err := cs.OpenWAL(walFile)
  141. require.NoError(t, err)
  142. crashingWal.next = csWal
  143. // reset the message counter
  144. crashingWal.msgIndex = 1
  145. cs.wal = crashingWal
  146. // start consensus state
  147. err = cs.Start()
  148. require.NoError(t, err)
  149. i++
  150. select {
  151. case err := <-walPanicked:
  152. t.Logf("WAL panicked: %v", err)
  153. // make sure we can make blocks after a crash
  154. startNewConsensusStateAndWaitForBlock(t, consensusReplayConfig, cs.Height, blockDB, stateDB)
  155. // stop consensus state and transactions sender (initFn)
  156. cs.Stop()
  157. cancel()
  158. // if we reached the required height, exit
  159. if _, ok := err.(ReachedHeightToStopError); ok {
  160. break LOOP
  161. }
  162. case <-time.After(10 * time.Second):
  163. t.Fatal("WAL did not panic for 10 seconds (check the log)")
  164. }
  165. }
  166. }
  167. // crashingWAL is a WAL which crashes or rather simulates a crash during Save
  168. // (before and after). It remembers a message for which we last panicked
  169. // (lastPanickedForMsgIndex), so we don't panic for it in subsequent iterations.
  170. type crashingWAL struct {
  171. next WAL
  172. panicCh chan error
  173. heightToStop int64
  174. msgIndex int // current message index
  175. lastPanickedForMsgIndex int // last message for which we panicked
  176. }
  177. var _ WAL = &crashingWAL{}
  178. // WALWriteError indicates a WAL crash.
  179. type WALWriteError struct {
  180. msg string
  181. }
  182. func (e WALWriteError) Error() string {
  183. return e.msg
  184. }
  185. // ReachedHeightToStopError indicates we've reached the required consensus
  186. // height and may exit.
  187. type ReachedHeightToStopError struct {
  188. height int64
  189. }
  190. func (e ReachedHeightToStopError) Error() string {
  191. return fmt.Sprintf("reached height to stop %d", e.height)
  192. }
  193. // Write simulate WAL's crashing by sending an error to the panicCh and then
  194. // exiting the cs.receiveRoutine.
  195. func (w *crashingWAL) Write(m WALMessage) {
  196. if endMsg, ok := m.(EndHeightMessage); ok {
  197. if endMsg.Height == w.heightToStop {
  198. w.panicCh <- ReachedHeightToStopError{endMsg.Height}
  199. runtime.Goexit()
  200. } else {
  201. w.next.Write(m)
  202. }
  203. return
  204. }
  205. if w.msgIndex > w.lastPanickedForMsgIndex {
  206. w.lastPanickedForMsgIndex = w.msgIndex
  207. _, file, line, _ := runtime.Caller(1)
  208. w.panicCh <- WALWriteError{fmt.Sprintf("failed to write %T to WAL (fileline: %s:%d)", m, file, line)}
  209. runtime.Goexit()
  210. } else {
  211. w.msgIndex++
  212. w.next.Write(m)
  213. }
  214. }
  215. func (w *crashingWAL) WriteSync(m WALMessage) {
  216. w.Write(m)
  217. }
  218. func (w *crashingWAL) FlushAndSync() error { return w.next.FlushAndSync() }
  219. func (w *crashingWAL) SearchForEndHeight(height int64, options *WALSearchOptions) (rd io.ReadCloser, found bool, err error) {
  220. return w.next.SearchForEndHeight(height, options)
  221. }
  222. func (w *crashingWAL) Start() error { return w.next.Start() }
  223. func (w *crashingWAL) Stop() error { return w.next.Stop() }
  224. func (w *crashingWAL) Wait() { w.next.Wait() }
  225. //------------------------------------------------------------------------------------------
  226. type testSim struct {
  227. GenesisState sm.State
  228. Config *cfg.Config
  229. Chain []*types.Block
  230. Commits []*types.Commit
  231. CleanupFunc cleanupFunc
  232. }
  233. const (
  234. numBlocks = 6
  235. )
  236. var (
  237. mempool = mock.Mempool{}
  238. evpool = sm.MockEvidencePool{}
  239. sim testSim
  240. )
  241. //---------------------------------------
  242. // Test handshake/replay
  243. // 0 - all synced up
  244. // 1 - saved block but app and state are behind
  245. // 2 - save block and committed but state is behind
  246. var modes = []uint{0, 1, 2}
  247. // This is actually not a test, it's for storing validator change tx data for testHandshakeReplay
  248. func TestSimulateValidatorsChange(t *testing.T) {
  249. nPeers := 7
  250. nVals := 4
  251. css, genDoc, config, cleanup := randConsensusNetWithPeers(nVals, nPeers, "replay_test", newMockTickerFunc(true), newPersistentKVStoreWithPath)
  252. sim.Config = config
  253. sim.GenesisState, _ = sm.MakeGenesisState(genDoc)
  254. sim.CleanupFunc = cleanup
  255. partSize := types.BlockPartSizeBytes
  256. newRoundCh := subscribe(css[0].eventBus, types.EventQueryNewRound)
  257. proposalCh := subscribe(css[0].eventBus, types.EventQueryCompleteProposal)
  258. vss := make([]*validatorStub, nPeers)
  259. for i := 0; i < nPeers; i++ {
  260. vss[i] = NewValidatorStub(css[i].privValidator, i)
  261. }
  262. height, round := css[0].Height, css[0].Round
  263. // start the machine
  264. startTestRound(css[0], height, round)
  265. incrementHeight(vss...)
  266. ensureNewRound(newRoundCh, height, 0)
  267. ensureNewProposal(proposalCh, height, round)
  268. rs := css[0].GetRoundState()
  269. signAddVotes(css[0], types.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...)
  270. ensureNewRound(newRoundCh, height+1, 0)
  271. //height 2
  272. height++
  273. incrementHeight(vss...)
  274. newValidatorPubKey1 := css[nVals].privValidator.GetPubKey()
  275. valPubKey1ABCI := types.TM2PB.PubKey(newValidatorPubKey1)
  276. newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower)
  277. err := assertMempool(css[0].txNotifier).CheckTx(newValidatorTx1, nil)
  278. assert.Nil(t, err)
  279. propBlock, _ := css[0].createProposalBlock() //changeProposer(t, cs1, vs2)
  280. propBlockParts := propBlock.MakePartSet(partSize)
  281. blockID := types.BlockID{Hash: propBlock.Hash(), PartsHeader: propBlockParts.Header()}
  282. proposal := types.NewProposal(vss[1].Height, round, -1, blockID)
  283. if err := vss[1].SignProposal(config.ChainID(), proposal); err != nil {
  284. t.Fatal("failed to sign bad proposal", err)
  285. }
  286. // set the proposal block
  287. if err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil {
  288. t.Fatal(err)
  289. }
  290. ensureNewProposal(proposalCh, height, round)
  291. rs = css[0].GetRoundState()
  292. signAddVotes(css[0], types.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...)
  293. ensureNewRound(newRoundCh, height+1, 0)
  294. //height 3
  295. height++
  296. incrementHeight(vss...)
  297. updateValidatorPubKey1 := css[nVals].privValidator.GetPubKey()
  298. updatePubKey1ABCI := types.TM2PB.PubKey(updateValidatorPubKey1)
  299. updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25)
  300. err = assertMempool(css[0].txNotifier).CheckTx(updateValidatorTx1, nil)
  301. assert.Nil(t, err)
  302. propBlock, _ = css[0].createProposalBlock() //changeProposer(t, cs1, vs2)
  303. propBlockParts = propBlock.MakePartSet(partSize)
  304. blockID = types.BlockID{Hash: propBlock.Hash(), PartsHeader: propBlockParts.Header()}
  305. proposal = types.NewProposal(vss[2].Height, round, -1, blockID)
  306. if err := vss[2].SignProposal(config.ChainID(), proposal); err != nil {
  307. t.Fatal("failed to sign bad proposal", err)
  308. }
  309. // set the proposal block
  310. if err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil {
  311. t.Fatal(err)
  312. }
  313. ensureNewProposal(proposalCh, height, round)
  314. rs = css[0].GetRoundState()
  315. signAddVotes(css[0], types.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...)
  316. ensureNewRound(newRoundCh, height+1, 0)
  317. //height 4
  318. height++
  319. incrementHeight(vss...)
  320. newValidatorPubKey2 := css[nVals+1].privValidator.GetPubKey()
  321. newVal2ABCI := types.TM2PB.PubKey(newValidatorPubKey2)
  322. newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower)
  323. err = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx2, nil)
  324. assert.Nil(t, err)
  325. newValidatorPubKey3 := css[nVals+2].privValidator.GetPubKey()
  326. newVal3ABCI := types.TM2PB.PubKey(newValidatorPubKey3)
  327. newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower)
  328. err = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx3, nil)
  329. assert.Nil(t, err)
  330. propBlock, _ = css[0].createProposalBlock() //changeProposer(t, cs1, vs2)
  331. propBlockParts = propBlock.MakePartSet(partSize)
  332. blockID = types.BlockID{Hash: propBlock.Hash(), PartsHeader: propBlockParts.Header()}
  333. newVss := make([]*validatorStub, nVals+1)
  334. copy(newVss, vss[:nVals+1])
  335. sort.Sort(ValidatorStubsByAddress(newVss))
  336. selfIndex := 0
  337. for i, vs := range newVss {
  338. if vs.GetPubKey().Equals(css[0].privValidator.GetPubKey()) {
  339. selfIndex = i
  340. break
  341. }
  342. }
  343. proposal = types.NewProposal(vss[3].Height, round, -1, blockID)
  344. if err := vss[3].SignProposal(config.ChainID(), proposal); err != nil {
  345. t.Fatal("failed to sign bad proposal", err)
  346. }
  347. // set the proposal block
  348. if err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil {
  349. t.Fatal(err)
  350. }
  351. ensureNewProposal(proposalCh, height, round)
  352. removeValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, 0)
  353. err = assertMempool(css[0].txNotifier).CheckTx(removeValidatorTx2, nil)
  354. assert.Nil(t, err)
  355. rs = css[0].GetRoundState()
  356. for i := 0; i < nVals+1; i++ {
  357. if i == selfIndex {
  358. continue
  359. }
  360. signAddVotes(css[0], types.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), newVss[i])
  361. }
  362. ensureNewRound(newRoundCh, height+1, 0)
  363. //height 5
  364. height++
  365. incrementHeight(vss...)
  366. ensureNewProposal(proposalCh, height, round)
  367. rs = css[0].GetRoundState()
  368. for i := 0; i < nVals+1; i++ {
  369. if i == selfIndex {
  370. continue
  371. }
  372. signAddVotes(css[0], types.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), newVss[i])
  373. }
  374. ensureNewRound(newRoundCh, height+1, 0)
  375. //height 6
  376. height++
  377. incrementHeight(vss...)
  378. removeValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, 0)
  379. err = assertMempool(css[0].txNotifier).CheckTx(removeValidatorTx3, nil)
  380. assert.Nil(t, err)
  381. propBlock, _ = css[0].createProposalBlock() //changeProposer(t, cs1, vs2)
  382. propBlockParts = propBlock.MakePartSet(partSize)
  383. blockID = types.BlockID{Hash: propBlock.Hash(), PartsHeader: propBlockParts.Header()}
  384. newVss = make([]*validatorStub, nVals+3)
  385. copy(newVss, vss[:nVals+3])
  386. sort.Sort(ValidatorStubsByAddress(newVss))
  387. for i, vs := range newVss {
  388. if vs.GetPubKey().Equals(css[0].privValidator.GetPubKey()) {
  389. selfIndex = i
  390. break
  391. }
  392. }
  393. proposal = types.NewProposal(vss[1].Height, round, -1, blockID)
  394. if err := vss[1].SignProposal(config.ChainID(), proposal); err != nil {
  395. t.Fatal("failed to sign bad proposal", err)
  396. }
  397. // set the proposal block
  398. if err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, "some peer"); err != nil {
  399. t.Fatal(err)
  400. }
  401. ensureNewProposal(proposalCh, height, round)
  402. rs = css[0].GetRoundState()
  403. for i := 0; i < nVals+3; i++ {
  404. if i == selfIndex {
  405. continue
  406. }
  407. signAddVotes(css[0], types.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), newVss[i])
  408. }
  409. ensureNewRound(newRoundCh, height+1, 0)
  410. sim.Chain = make([]*types.Block, 0)
  411. sim.Commits = make([]*types.Commit, 0)
  412. for i := 1; i <= numBlocks; i++ {
  413. sim.Chain = append(sim.Chain, css[0].blockStore.LoadBlock(int64(i)))
  414. sim.Commits = append(sim.Commits, css[0].blockStore.LoadBlockCommit(int64(i)))
  415. }
  416. }
  417. // Sync from scratch
  418. func TestHandshakeReplayAll(t *testing.T) {
  419. for _, m := range modes {
  420. testHandshakeReplay(t, config, 0, m, false)
  421. }
  422. for _, m := range modes {
  423. testHandshakeReplay(t, config, 0, m, true)
  424. }
  425. }
  426. // Sync many, not from scratch
  427. func TestHandshakeReplaySome(t *testing.T) {
  428. for _, m := range modes {
  429. testHandshakeReplay(t, config, 1, m, false)
  430. }
  431. for _, m := range modes {
  432. testHandshakeReplay(t, config, 1, m, true)
  433. }
  434. }
  435. // Sync from lagging by one
  436. func TestHandshakeReplayOne(t *testing.T) {
  437. for _, m := range modes {
  438. testHandshakeReplay(t, config, numBlocks-1, m, false)
  439. }
  440. for _, m := range modes {
  441. testHandshakeReplay(t, config, numBlocks-1, m, true)
  442. }
  443. }
  444. // Sync from caught up
  445. func TestHandshakeReplayNone(t *testing.T) {
  446. for _, m := range modes {
  447. testHandshakeReplay(t, config, numBlocks, m, false)
  448. }
  449. for _, m := range modes {
  450. testHandshakeReplay(t, config, numBlocks, m, true)
  451. }
  452. }
  453. // Test mockProxyApp should not panic when app return ABCIResponses with some empty ResponseDeliverTx
  454. func TestMockProxyApp(t *testing.T) {
  455. sim.CleanupFunc() //clean the test env created in TestSimulateValidatorsChange
  456. logger := log.TestingLogger()
  457. var validTxs, invalidTxs = 0, 0
  458. txIndex := 0
  459. assert.NotPanics(t, func() {
  460. abciResWithEmptyDeliverTx := new(sm.ABCIResponses)
  461. abciResWithEmptyDeliverTx.DeliverTx = make([]*abci.ResponseDeliverTx, 0)
  462. abciResWithEmptyDeliverTx.DeliverTx = append(abciResWithEmptyDeliverTx.DeliverTx, &abci.ResponseDeliverTx{})
  463. // called when saveABCIResponses:
  464. bytes := cdc.MustMarshalBinaryBare(abciResWithEmptyDeliverTx)
  465. loadedAbciRes := new(sm.ABCIResponses)
  466. // this also happens sm.LoadABCIResponses
  467. err := cdc.UnmarshalBinaryBare(bytes, loadedAbciRes)
  468. require.NoError(t, err)
  469. mock := newMockProxyApp([]byte("mock_hash"), loadedAbciRes)
  470. abciRes := new(sm.ABCIResponses)
  471. abciRes.DeliverTx = make([]*abci.ResponseDeliverTx, len(loadedAbciRes.DeliverTx))
  472. // Execute transactions and get hash.
  473. proxyCb := func(req *abci.Request, res *abci.Response) {
  474. if r, ok := res.Value.(*abci.Response_DeliverTx); ok {
  475. // TODO: make use of res.Log
  476. // TODO: make use of this info
  477. // Blocks may include invalid txs.
  478. txRes := r.DeliverTx
  479. if txRes.Code == abci.CodeTypeOK {
  480. validTxs++
  481. } else {
  482. logger.Debug("Invalid tx", "code", txRes.Code, "log", txRes.Log)
  483. invalidTxs++
  484. }
  485. abciRes.DeliverTx[txIndex] = txRes
  486. txIndex++
  487. }
  488. }
  489. mock.SetResponseCallback(proxyCb)
  490. someTx := []byte("tx")
  491. mock.DeliverTxAsync(abci.RequestDeliverTx{Tx: someTx})
  492. })
  493. assert.True(t, validTxs == 1)
  494. assert.True(t, invalidTxs == 0)
  495. }
  496. func tempWALWithData(data []byte) string {
  497. walFile, err := ioutil.TempFile("", "wal")
  498. if err != nil {
  499. panic(fmt.Sprintf("failed to create temp WAL file: %v", err))
  500. }
  501. _, err = walFile.Write(data)
  502. if err != nil {
  503. panic(fmt.Sprintf("failed to write to temp WAL file: %v", err))
  504. }
  505. if err := walFile.Close(); err != nil {
  506. panic(fmt.Sprintf("failed to close temp WAL file: %v", err))
  507. }
  508. return walFile.Name()
  509. }
  510. // Make some blocks. Start a fresh app and apply nBlocks blocks. Then restart the app and sync it up with the remaining blocks
  511. func testHandshakeReplay(t *testing.T, config *cfg.Config, nBlocks int, mode uint, testValidatorsChange bool) {
  512. var chain []*types.Block
  513. var commits []*types.Commit
  514. var store *mockBlockStore
  515. var stateDB dbm.DB
  516. var genisisState sm.State
  517. if testValidatorsChange {
  518. testConfig := ResetConfig(fmt.Sprintf("%s_%v_m", t.Name(), mode))
  519. defer os.RemoveAll(testConfig.RootDir)
  520. stateDB = dbm.NewMemDB()
  521. genisisState = sim.GenesisState
  522. config = sim.Config
  523. chain = sim.Chain
  524. commits = sim.Commits
  525. store = newMockBlockStore(config, genisisState.ConsensusParams)
  526. } else { //test single node
  527. testConfig := ResetConfig(fmt.Sprintf("%s_%v_s", t.Name(), mode))
  528. defer os.RemoveAll(testConfig.RootDir)
  529. walBody, err := WALWithNBlocks(t, numBlocks)
  530. require.NoError(t, err)
  531. walFile := tempWALWithData(walBody)
  532. config.Consensus.SetWalFile(walFile)
  533. privVal := privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile())
  534. wal, err := NewWAL(walFile)
  535. require.NoError(t, err)
  536. wal.SetLogger(log.TestingLogger())
  537. err = wal.Start()
  538. require.NoError(t, err)
  539. defer wal.Stop()
  540. chain, commits, err = makeBlockchainFromWAL(wal)
  541. require.NoError(t, err)
  542. stateDB, genisisState, store = stateAndStore(config, privVal.GetPubKey(), kvstore.ProtocolVersion)
  543. }
  544. store.chain = chain
  545. store.commits = commits
  546. state := genisisState.Copy()
  547. // run the chain through state.ApplyBlock to build up the tendermint state
  548. state = buildTMStateFromChain(config, stateDB, state, chain, nBlocks, mode)
  549. latestAppHash := state.AppHash
  550. // make a new client creator
  551. kvstoreApp := kvstore.NewPersistentKVStoreApplication(filepath.Join(config.DBDir(), fmt.Sprintf("replay_test_%d_%d_a", nBlocks, mode)))
  552. clientCreator2 := proxy.NewLocalClientCreator(kvstoreApp)
  553. if nBlocks > 0 {
  554. // run nBlocks against a new client to build up the app state.
  555. // use a throwaway tendermint state
  556. proxyApp := proxy.NewAppConns(clientCreator2)
  557. stateDB1 := dbm.NewMemDB()
  558. sm.SaveState(stateDB1, genisisState)
  559. buildAppStateFromChain(proxyApp, stateDB1, genisisState, chain, nBlocks, mode)
  560. }
  561. // now start the app using the handshake - it should sync
  562. genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())
  563. handshaker := NewHandshaker(stateDB, state, store, genDoc)
  564. proxyApp := proxy.NewAppConns(clientCreator2)
  565. if err := proxyApp.Start(); err != nil {
  566. t.Fatalf("Error starting proxy app connections: %v", err)
  567. }
  568. defer proxyApp.Stop()
  569. if err := handshaker.Handshake(proxyApp); err != nil {
  570. t.Fatalf("Error on abci handshake: %v", err)
  571. }
  572. // get the latest app hash from the app
  573. res, err := proxyApp.Query().InfoSync(abci.RequestInfo{Version: ""})
  574. if err != nil {
  575. t.Fatal(err)
  576. }
  577. // the app hash should be synced up
  578. if !bytes.Equal(latestAppHash, res.LastBlockAppHash) {
  579. t.Fatalf("Expected app hashes to match after handshake/replay. got %X, expected %X", res.LastBlockAppHash, latestAppHash)
  580. }
  581. expectedBlocksToSync := numBlocks - nBlocks
  582. if nBlocks == numBlocks && mode > 0 {
  583. expectedBlocksToSync++
  584. } else if nBlocks > 0 && mode == 1 {
  585. expectedBlocksToSync++
  586. }
  587. if handshaker.NBlocks() != expectedBlocksToSync {
  588. t.Fatalf("Expected handshake to sync %d blocks, got %d", expectedBlocksToSync, handshaker.NBlocks())
  589. }
  590. }
  591. func applyBlock(stateDB dbm.DB, st sm.State, blk *types.Block, proxyApp proxy.AppConns) sm.State {
  592. testPartSize := types.BlockPartSizeBytes
  593. blockExec := sm.NewBlockExecutor(stateDB, log.TestingLogger(), proxyApp.Consensus(), mempool, evpool)
  594. blkID := types.BlockID{Hash: blk.Hash(), PartsHeader: blk.MakePartSet(testPartSize).Header()}
  595. newState, err := blockExec.ApplyBlock(st, blkID, blk)
  596. if err != nil {
  597. panic(err)
  598. }
  599. return newState
  600. }
  601. func buildAppStateFromChain(proxyApp proxy.AppConns, stateDB dbm.DB,
  602. state sm.State, chain []*types.Block, nBlocks int, mode uint) {
  603. // start a new app without handshake, play nBlocks blocks
  604. if err := proxyApp.Start(); err != nil {
  605. panic(err)
  606. }
  607. defer proxyApp.Stop()
  608. state.Version.Consensus.App = kvstore.ProtocolVersion //simulate handshake, receive app version
  609. validators := types.TM2PB.ValidatorUpdates(state.Validators)
  610. if _, err := proxyApp.Consensus().InitChainSync(abci.RequestInitChain{
  611. Validators: validators,
  612. }); err != nil {
  613. panic(err)
  614. }
  615. sm.SaveState(stateDB, state) //save height 1's validatorsInfo
  616. switch mode {
  617. case 0:
  618. for i := 0; i < nBlocks; i++ {
  619. block := chain[i]
  620. state = applyBlock(stateDB, state, block, proxyApp)
  621. }
  622. case 1, 2:
  623. for i := 0; i < nBlocks-1; i++ {
  624. block := chain[i]
  625. state = applyBlock(stateDB, state, block, proxyApp)
  626. }
  627. if mode == 2 {
  628. // update the kvstore height and apphash
  629. // as if we ran commit but not
  630. state = applyBlock(stateDB, state, chain[nBlocks-1], proxyApp)
  631. }
  632. }
  633. }
  634. func buildTMStateFromChain(config *cfg.Config, stateDB dbm.DB, state sm.State, chain []*types.Block, nBlocks int, mode uint) sm.State {
  635. // run the whole chain against this client to build up the tendermint state
  636. clientCreator := proxy.NewLocalClientCreator(kvstore.NewPersistentKVStoreApplication(filepath.Join(config.DBDir(), fmt.Sprintf("replay_test_%d_%d_t", nBlocks, mode))))
  637. proxyApp := proxy.NewAppConns(clientCreator)
  638. if err := proxyApp.Start(); err != nil {
  639. panic(err)
  640. }
  641. defer proxyApp.Stop()
  642. state.Version.Consensus.App = kvstore.ProtocolVersion //simulate handshake, receive app version
  643. validators := types.TM2PB.ValidatorUpdates(state.Validators)
  644. if _, err := proxyApp.Consensus().InitChainSync(abci.RequestInitChain{
  645. Validators: validators,
  646. }); err != nil {
  647. panic(err)
  648. }
  649. sm.SaveState(stateDB, state) //save height 1's validatorsInfo
  650. switch mode {
  651. case 0:
  652. // sync right up
  653. for _, block := range chain {
  654. state = applyBlock(stateDB, state, block, proxyApp)
  655. }
  656. case 1, 2:
  657. // sync up to the penultimate as if we stored the block.
  658. // whether we commit or not depends on the appHash
  659. for _, block := range chain[:len(chain)-1] {
  660. state = applyBlock(stateDB, state, block, proxyApp)
  661. }
  662. // apply the final block to a state copy so we can
  663. // get the right next appHash but keep the state back
  664. applyBlock(stateDB, state, chain[len(chain)-1], proxyApp)
  665. }
  666. return state
  667. }
  668. func TestHandshakePanicsIfAppReturnsWrongAppHash(t *testing.T) {
  669. // 1. Initialize tendermint and commit 3 blocks with the following app hashes:
  670. // - 0x01
  671. // - 0x02
  672. // - 0x03
  673. config := ResetConfig("handshake_test_")
  674. defer os.RemoveAll(config.RootDir)
  675. privVal := privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile())
  676. const appVersion = 0x0
  677. stateDB, state, store := stateAndStore(config, privVal.GetPubKey(), appVersion)
  678. genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())
  679. state.LastValidators = state.Validators.Copy()
  680. // mode = 0 for committing all the blocks
  681. blocks := makeBlocks(3, &state, privVal)
  682. store.chain = blocks
  683. // 2. Tendermint must panic if app returns wrong hash for the first block
  684. // - RANDOM HASH
  685. // - 0x02
  686. // - 0x03
  687. {
  688. app := &badApp{numBlocks: 3, allHashesAreWrong: true}
  689. clientCreator := proxy.NewLocalClientCreator(app)
  690. proxyApp := proxy.NewAppConns(clientCreator)
  691. err := proxyApp.Start()
  692. require.NoError(t, err)
  693. defer proxyApp.Stop()
  694. assert.Panics(t, func() {
  695. h := NewHandshaker(stateDB, state, store, genDoc)
  696. h.Handshake(proxyApp)
  697. })
  698. }
  699. // 3. Tendermint must panic if app returns wrong hash for the last block
  700. // - 0x01
  701. // - 0x02
  702. // - RANDOM HASH
  703. {
  704. app := &badApp{numBlocks: 3, onlyLastHashIsWrong: true}
  705. clientCreator := proxy.NewLocalClientCreator(app)
  706. proxyApp := proxy.NewAppConns(clientCreator)
  707. err := proxyApp.Start()
  708. require.NoError(t, err)
  709. defer proxyApp.Stop()
  710. assert.Panics(t, func() {
  711. h := NewHandshaker(stateDB, state, store, genDoc)
  712. h.Handshake(proxyApp)
  713. })
  714. }
  715. }
  716. func makeBlocks(n int, state *sm.State, privVal types.PrivValidator) []*types.Block {
  717. blocks := make([]*types.Block, 0)
  718. var (
  719. prevBlock *types.Block
  720. prevBlockMeta *types.BlockMeta
  721. )
  722. appHeight := byte(0x01)
  723. for i := 0; i < n; i++ {
  724. height := int64(i + 1)
  725. block, parts := makeBlock(*state, prevBlock, prevBlockMeta, privVal, height)
  726. blocks = append(blocks, block)
  727. prevBlock = block
  728. prevBlockMeta = types.NewBlockMeta(block, parts)
  729. // update state
  730. state.AppHash = []byte{appHeight}
  731. appHeight++
  732. state.LastBlockHeight = height
  733. }
  734. return blocks
  735. }
  736. func makeBlock(state sm.State, lastBlock *types.Block, lastBlockMeta *types.BlockMeta,
  737. privVal types.PrivValidator, height int64) (*types.Block, *types.PartSet) {
  738. lastCommit := types.NewCommit(types.BlockID{}, nil)
  739. if height > 1 {
  740. vote, _ := types.MakeVote(lastBlock.Header.Height, lastBlockMeta.BlockID, state.Validators, privVal, lastBlock.Header.ChainID)
  741. voteCommitSig := vote.CommitSig()
  742. lastCommit = types.NewCommit(lastBlockMeta.BlockID, []*types.CommitSig{voteCommitSig})
  743. }
  744. return state.MakeBlock(height, []types.Tx{}, lastCommit, nil, state.Validators.GetProposer().Address)
  745. }
  746. type badApp struct {
  747. abci.BaseApplication
  748. numBlocks byte
  749. height byte
  750. allHashesAreWrong bool
  751. onlyLastHashIsWrong bool
  752. }
  753. func (app *badApp) Commit() abci.ResponseCommit {
  754. app.height++
  755. if app.onlyLastHashIsWrong {
  756. if app.height == app.numBlocks {
  757. return abci.ResponseCommit{Data: cmn.RandBytes(8)}
  758. }
  759. return abci.ResponseCommit{Data: []byte{app.height}}
  760. } else if app.allHashesAreWrong {
  761. return abci.ResponseCommit{Data: cmn.RandBytes(8)}
  762. }
  763. panic("either allHashesAreWrong or onlyLastHashIsWrong must be set")
  764. }
  765. //--------------------------
  766. // utils for making blocks
  767. func makeBlockchainFromWAL(wal WAL) ([]*types.Block, []*types.Commit, error) {
  768. var height int64
  769. // Search for height marker
  770. gr, found, err := wal.SearchForEndHeight(height, &WALSearchOptions{})
  771. if err != nil {
  772. return nil, nil, err
  773. }
  774. if !found {
  775. return nil, nil, fmt.Errorf("WAL does not contain height %d", height)
  776. }
  777. defer gr.Close() // nolint: errcheck
  778. // log.Notice("Build a blockchain by reading from the WAL")
  779. var (
  780. blocks []*types.Block
  781. commits []*types.Commit
  782. thisBlockParts *types.PartSet
  783. thisBlockCommit *types.Commit
  784. )
  785. dec := NewWALDecoder(gr)
  786. for {
  787. msg, err := dec.Decode()
  788. if err == io.EOF {
  789. break
  790. } else if err != nil {
  791. return nil, nil, err
  792. }
  793. piece := readPieceFromWAL(msg)
  794. if piece == nil {
  795. continue
  796. }
  797. switch p := piece.(type) {
  798. case EndHeightMessage:
  799. // if its not the first one, we have a full block
  800. if thisBlockParts != nil {
  801. var block = new(types.Block)
  802. _, err = cdc.UnmarshalBinaryLengthPrefixedReader(thisBlockParts.GetReader(), block, 0)
  803. if err != nil {
  804. panic(err)
  805. }
  806. if block.Height != height+1 {
  807. panic(fmt.Sprintf("read bad block from wal. got height %d, expected %d", block.Height, height+1))
  808. }
  809. commitHeight := thisBlockCommit.Precommits[0].Height
  810. if commitHeight != height+1 {
  811. panic(fmt.Sprintf("commit doesnt match. got height %d, expected %d", commitHeight, height+1))
  812. }
  813. blocks = append(blocks, block)
  814. commits = append(commits, thisBlockCommit)
  815. height++
  816. }
  817. case *types.PartSetHeader:
  818. thisBlockParts = types.NewPartSetFromHeader(*p)
  819. case *types.Part:
  820. _, err := thisBlockParts.AddPart(p)
  821. if err != nil {
  822. return nil, nil, err
  823. }
  824. case *types.Vote:
  825. if p.Type == types.PrecommitType {
  826. commitSigs := []*types.CommitSig{p.CommitSig()}
  827. thisBlockCommit = types.NewCommit(p.BlockID, commitSigs)
  828. }
  829. }
  830. }
  831. // grab the last block too
  832. var block = new(types.Block)
  833. _, err = cdc.UnmarshalBinaryLengthPrefixedReader(thisBlockParts.GetReader(), block, 0)
  834. if err != nil {
  835. panic(err)
  836. }
  837. if block.Height != height+1 {
  838. panic(fmt.Sprintf("read bad block from wal. got height %d, expected %d", block.Height, height+1))
  839. }
  840. commitHeight := thisBlockCommit.Precommits[0].Height
  841. if commitHeight != height+1 {
  842. panic(fmt.Sprintf("commit doesnt match. got height %d, expected %d", commitHeight, height+1))
  843. }
  844. blocks = append(blocks, block)
  845. commits = append(commits, thisBlockCommit)
  846. return blocks, commits, nil
  847. }
  848. func readPieceFromWAL(msg *TimedWALMessage) interface{} {
  849. // for logging
  850. switch m := msg.Msg.(type) {
  851. case msgInfo:
  852. switch msg := m.Msg.(type) {
  853. case *ProposalMessage:
  854. return &msg.Proposal.BlockID.PartsHeader
  855. case *BlockPartMessage:
  856. return msg.Part
  857. case *VoteMessage:
  858. return msg.Vote
  859. }
  860. case EndHeightMessage:
  861. return m
  862. }
  863. return nil
  864. }
  865. // fresh state and mock store
  866. func stateAndStore(config *cfg.Config, pubKey crypto.PubKey, appVersion version.Protocol) (dbm.DB, sm.State, *mockBlockStore) {
  867. stateDB := dbm.NewMemDB()
  868. state, _ := sm.MakeGenesisStateFromFile(config.GenesisFile())
  869. state.Version.Consensus.App = appVersion
  870. store := newMockBlockStore(config, state.ConsensusParams)
  871. sm.SaveState(stateDB, state)
  872. return stateDB, state, store
  873. }
  874. //----------------------------------
  875. // mock block store
  876. type mockBlockStore struct {
  877. config *cfg.Config
  878. params types.ConsensusParams
  879. chain []*types.Block
  880. commits []*types.Commit
  881. }
  882. // TODO: NewBlockStore(db.NewMemDB) ...
  883. func newMockBlockStore(config *cfg.Config, params types.ConsensusParams) *mockBlockStore {
  884. return &mockBlockStore{config, params, nil, nil}
  885. }
  886. func (bs *mockBlockStore) Height() int64 { return int64(len(bs.chain)) }
  887. func (bs *mockBlockStore) LoadBlock(height int64) *types.Block { return bs.chain[height-1] }
  888. func (bs *mockBlockStore) LoadBlockMeta(height int64) *types.BlockMeta {
  889. block := bs.chain[height-1]
  890. return &types.BlockMeta{
  891. BlockID: types.BlockID{Hash: block.Hash(), PartsHeader: block.MakePartSet(types.BlockPartSizeBytes).Header()},
  892. Header: block.Header,
  893. }
  894. }
  895. func (bs *mockBlockStore) LoadBlockPart(height int64, index int) *types.Part { return nil }
  896. func (bs *mockBlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {
  897. }
  898. func (bs *mockBlockStore) LoadBlockCommit(height int64) *types.Commit {
  899. return bs.commits[height-1]
  900. }
  901. func (bs *mockBlockStore) LoadSeenCommit(height int64) *types.Commit {
  902. return bs.commits[height-1]
  903. }
  904. //---------------------------------------
  905. // Test handshake/init chain
  906. func TestHandshakeUpdatesValidators(t *testing.T) {
  907. val, _ := types.RandValidator(true, 10)
  908. vals := types.NewValidatorSet([]*types.Validator{val})
  909. app := &initChainApp{vals: types.TM2PB.ValidatorUpdates(vals)}
  910. clientCreator := proxy.NewLocalClientCreator(app)
  911. config := ResetConfig("handshake_test_")
  912. defer os.RemoveAll(config.RootDir)
  913. privVal := privval.LoadFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile())
  914. stateDB, state, store := stateAndStore(config, privVal.GetPubKey(), 0x0)
  915. oldValAddr := state.Validators.Validators[0].Address
  916. // now start the app using the handshake - it should sync
  917. genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())
  918. handshaker := NewHandshaker(stateDB, state, store, genDoc)
  919. proxyApp := proxy.NewAppConns(clientCreator)
  920. if err := proxyApp.Start(); err != nil {
  921. t.Fatalf("Error starting proxy app connections: %v", err)
  922. }
  923. defer proxyApp.Stop()
  924. if err := handshaker.Handshake(proxyApp); err != nil {
  925. t.Fatalf("Error on abci handshake: %v", err)
  926. }
  927. // reload the state, check the validator set was updated
  928. state = sm.LoadState(stateDB)
  929. newValAddr := state.Validators.Validators[0].Address
  930. expectValAddr := val.Address
  931. assert.NotEqual(t, oldValAddr, newValAddr)
  932. assert.Equal(t, newValAddr, expectValAddr)
  933. }
  934. // returns the vals on InitChain
  935. type initChainApp struct {
  936. abci.BaseApplication
  937. vals []abci.ValidatorUpdate
  938. }
  939. func (ica *initChainApp) InitChain(req abci.RequestInitChain) abci.ResponseInitChain {
  940. return abci.ResponseInitChain{
  941. Validators: ica.vals,
  942. }
  943. }