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.

556 lines
16 KiB

blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
  1. package store
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os"
  6. "runtime/debug"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/require"
  12. dbm "github.com/tendermint/tm-db"
  13. cfg "github.com/tendermint/tendermint/config"
  14. "github.com/tendermint/tendermint/libs/log"
  15. sm "github.com/tendermint/tendermint/state"
  16. "github.com/tendermint/tendermint/types"
  17. tmtime "github.com/tendermint/tendermint/types/time"
  18. )
  19. // A cleanupFunc cleans up any config / test files created for a particular
  20. // test.
  21. type cleanupFunc func()
  22. // make a Commit with a single vote containing just the height and a timestamp
  23. func makeTestCommit(height int64, timestamp time.Time) *types.Commit {
  24. commitSigs := []types.CommitSig{{
  25. BlockIDFlag: types.BlockIDFlagCommit,
  26. ValidatorAddress: []byte("ValidatorAddress"),
  27. Timestamp: timestamp,
  28. Signature: []byte("Signature"),
  29. }}
  30. return types.NewCommit(height, 0, types.BlockID{}, commitSigs)
  31. }
  32. func makeTxs(height int64) (txs []types.Tx) {
  33. for i := 0; i < 10; i++ {
  34. txs = append(txs, types.Tx([]byte{byte(height), byte(i)}))
  35. }
  36. return txs
  37. }
  38. func makeBlock(height int64, state sm.State, lastCommit *types.Commit) *types.Block {
  39. block, _ := state.MakeBlock(height, makeTxs(height), lastCommit, nil, state.Validators.GetProposer().Address)
  40. return block
  41. }
  42. func makeStateAndBlockStore(logger log.Logger) (sm.State, *BlockStore, cleanupFunc) {
  43. config := cfg.ResetTestRoot("blockchain_reactor_test")
  44. // blockDB := dbm.NewDebugDB("blockDB", dbm.NewMemDB())
  45. // stateDB := dbm.NewDebugDB("stateDB", dbm.NewMemDB())
  46. blockDB := dbm.NewMemDB()
  47. stateDB := dbm.NewMemDB()
  48. state, err := sm.LoadStateFromDBOrGenesisFile(stateDB, config.GenesisFile())
  49. if err != nil {
  50. panic(fmt.Errorf("error constructing state from genesis file: %w", err))
  51. }
  52. return state, NewBlockStore(blockDB), func() { os.RemoveAll(config.RootDir) }
  53. }
  54. func TestLoadBlockStoreStateJSON(t *testing.T) {
  55. db := dbm.NewMemDB()
  56. bsj := &BlockStoreStateJSON{Base: 100, Height: 1000}
  57. bsj.Save(db)
  58. retrBSJ := LoadBlockStoreStateJSON(db)
  59. assert.Equal(t, *bsj, retrBSJ, "expected the retrieved DBs to match")
  60. }
  61. func TestLoadBlockStoreStateJSON_Empty(t *testing.T) {
  62. db := dbm.NewMemDB()
  63. bsj := &BlockStoreStateJSON{}
  64. bsj.Save(db)
  65. retrBSJ := LoadBlockStoreStateJSON(db)
  66. assert.Equal(t, BlockStoreStateJSON{}, retrBSJ, "expected the retrieved DBs to match")
  67. }
  68. func TestLoadBlockStoreStateJSON_NoBase(t *testing.T) {
  69. db := dbm.NewMemDB()
  70. bsj := &BlockStoreStateJSON{Height: 1000}
  71. bsj.Save(db)
  72. retrBSJ := LoadBlockStoreStateJSON(db)
  73. assert.Equal(t, BlockStoreStateJSON{Base: 1, Height: 1000}, retrBSJ, "expected the retrieved DBs to match")
  74. }
  75. func TestNewBlockStore(t *testing.T) {
  76. db := dbm.NewMemDB()
  77. err := db.Set(blockStoreKey, []byte(`{"base": "100", "height": "10000"}`))
  78. require.NoError(t, err)
  79. bs := NewBlockStore(db)
  80. require.Equal(t, int64(100), bs.Base(), "failed to properly parse blockstore")
  81. require.Equal(t, int64(10000), bs.Height(), "failed to properly parse blockstore")
  82. panicCausers := []struct {
  83. data []byte
  84. wantErr string
  85. }{
  86. {[]byte("artful-doger"), "not unmarshal bytes"},
  87. {[]byte(" "), "unmarshal bytes"},
  88. }
  89. for i, tt := range panicCausers {
  90. tt := tt
  91. // Expecting a panic here on trying to parse an invalid blockStore
  92. _, _, panicErr := doFn(func() (interface{}, error) {
  93. err := db.Set(blockStoreKey, tt.data)
  94. require.NoError(t, err)
  95. _ = NewBlockStore(db)
  96. return nil, nil
  97. })
  98. require.NotNil(t, panicErr, "#%d panicCauser: %q expected a panic", i, tt.data)
  99. assert.Contains(t, fmt.Sprintf("%#v", panicErr), tt.wantErr, "#%d data: %q", i, tt.data)
  100. }
  101. err = db.Set(blockStoreKey, nil)
  102. require.NoError(t, err)
  103. bs = NewBlockStore(db)
  104. assert.Equal(t, bs.Height(), int64(0), "expecting nil bytes to be unmarshaled alright")
  105. }
  106. func freshBlockStore() (*BlockStore, dbm.DB) {
  107. db := dbm.NewMemDB()
  108. return NewBlockStore(db), db
  109. }
  110. var (
  111. state sm.State
  112. block *types.Block
  113. partSet *types.PartSet
  114. part1 *types.Part
  115. part2 *types.Part
  116. seenCommit1 *types.Commit
  117. )
  118. func TestMain(m *testing.M) {
  119. var cleanup cleanupFunc
  120. state, _, cleanup = makeStateAndBlockStore(log.NewTMLogger(new(bytes.Buffer)))
  121. block = makeBlock(1, state, new(types.Commit))
  122. partSet = block.MakePartSet(2)
  123. part1 = partSet.GetPart(0)
  124. part2 = partSet.GetPart(1)
  125. seenCommit1 = makeTestCommit(10, tmtime.Now())
  126. code := m.Run()
  127. cleanup()
  128. os.Exit(code)
  129. }
  130. // TODO: This test should be simplified ...
  131. func TestBlockStoreSaveLoadBlock(t *testing.T) {
  132. state, bs, cleanup := makeStateAndBlockStore(log.NewTMLogger(new(bytes.Buffer)))
  133. defer cleanup()
  134. require.Equal(t, bs.Base(), int64(0), "initially the base should be zero")
  135. require.Equal(t, bs.Height(), int64(0), "initially the height should be zero")
  136. // check there are no blocks at various heights
  137. noBlockHeights := []int64{0, -1, 100, 1000, 2}
  138. for i, height := range noBlockHeights {
  139. if g := bs.LoadBlock(height); g != nil {
  140. t.Errorf("#%d: height(%d) got a block; want nil", i, height)
  141. }
  142. }
  143. // save a block
  144. block := makeBlock(bs.Height()+1, state, new(types.Commit))
  145. validPartSet := block.MakePartSet(2)
  146. seenCommit := makeTestCommit(10, tmtime.Now())
  147. bs.SaveBlock(block, partSet, seenCommit)
  148. require.EqualValues(t, 1, bs.Base(), "expecting the new height to be changed")
  149. require.EqualValues(t, block.Header.Height, bs.Height(), "expecting the new height to be changed")
  150. incompletePartSet := types.NewPartSetFromHeader(types.PartSetHeader{Total: 2})
  151. uncontiguousPartSet := types.NewPartSetFromHeader(types.PartSetHeader{Total: 0})
  152. uncontiguousPartSet.AddPart(part2)
  153. header1 := types.Header{
  154. Height: 1,
  155. ChainID: "block_test",
  156. Time: tmtime.Now(),
  157. }
  158. // End of setup, test data
  159. commitAtH10 := makeTestCommit(10, tmtime.Now())
  160. tuples := []struct {
  161. block *types.Block
  162. parts *types.PartSet
  163. seenCommit *types.Commit
  164. wantPanic string
  165. wantErr bool
  166. corruptBlockInDB bool
  167. corruptCommitInDB bool
  168. corruptSeenCommitInDB bool
  169. eraseCommitInDB bool
  170. eraseSeenCommitInDB bool
  171. }{
  172. {
  173. block: newBlock(header1, commitAtH10),
  174. parts: validPartSet,
  175. seenCommit: seenCommit1,
  176. },
  177. {
  178. block: nil,
  179. wantPanic: "only save a non-nil block",
  180. },
  181. {
  182. block: newBlock( // New block at height 5 in empty block store is fine
  183. types.Header{Height: 5, ChainID: "block_test", Time: tmtime.Now()},
  184. makeTestCommit(5, tmtime.Now()),
  185. ),
  186. parts: validPartSet,
  187. seenCommit: makeTestCommit(5, tmtime.Now()),
  188. },
  189. {
  190. block: newBlock(header1, commitAtH10),
  191. parts: incompletePartSet,
  192. wantPanic: "only save complete block", // incomplete parts
  193. },
  194. {
  195. block: newBlock(header1, commitAtH10),
  196. parts: validPartSet,
  197. seenCommit: seenCommit1,
  198. corruptCommitInDB: true, // Corrupt the DB's commit entry
  199. wantPanic: "unmarshal to types.Commit failed",
  200. },
  201. {
  202. block: newBlock(header1, commitAtH10),
  203. parts: validPartSet,
  204. seenCommit: seenCommit1,
  205. wantPanic: "unmarshal to types.BlockMeta failed",
  206. corruptBlockInDB: true, // Corrupt the DB's block entry
  207. },
  208. {
  209. block: newBlock(header1, commitAtH10),
  210. parts: validPartSet,
  211. seenCommit: seenCommit1,
  212. // Expecting no error and we want a nil back
  213. eraseSeenCommitInDB: true,
  214. },
  215. {
  216. block: newBlock(header1, commitAtH10),
  217. parts: validPartSet,
  218. seenCommit: seenCommit1,
  219. corruptSeenCommitInDB: true,
  220. wantPanic: "unmarshal to types.Commit failed",
  221. },
  222. {
  223. block: newBlock(header1, commitAtH10),
  224. parts: validPartSet,
  225. seenCommit: seenCommit1,
  226. // Expecting no error and we want a nil back
  227. eraseCommitInDB: true,
  228. },
  229. }
  230. type quad struct {
  231. block *types.Block
  232. commit *types.Commit
  233. meta *types.BlockMeta
  234. seenCommit *types.Commit
  235. }
  236. for i, tuple := range tuples {
  237. tuple := tuple
  238. bs, db := freshBlockStore()
  239. // SaveBlock
  240. res, err, panicErr := doFn(func() (interface{}, error) {
  241. bs.SaveBlock(tuple.block, tuple.parts, tuple.seenCommit)
  242. if tuple.block == nil {
  243. return nil, nil
  244. }
  245. if tuple.corruptBlockInDB {
  246. err := db.Set(calcBlockMetaKey(tuple.block.Height), []byte("block-bogus"))
  247. require.NoError(t, err)
  248. }
  249. bBlock := bs.LoadBlock(tuple.block.Height)
  250. bBlockMeta := bs.LoadBlockMeta(tuple.block.Height)
  251. if tuple.eraseSeenCommitInDB {
  252. db.Delete(calcSeenCommitKey(tuple.block.Height))
  253. }
  254. if tuple.corruptSeenCommitInDB {
  255. err := db.Set(calcSeenCommitKey(tuple.block.Height), []byte("bogus-seen-commit"))
  256. require.NoError(t, err)
  257. }
  258. bSeenCommit := bs.LoadSeenCommit(tuple.block.Height)
  259. commitHeight := tuple.block.Height - 1
  260. if tuple.eraseCommitInDB {
  261. db.Delete(calcBlockCommitKey(commitHeight))
  262. }
  263. if tuple.corruptCommitInDB {
  264. err := db.Set(calcBlockCommitKey(commitHeight), []byte("foo-bogus"))
  265. require.NoError(t, err)
  266. }
  267. bCommit := bs.LoadBlockCommit(commitHeight)
  268. return &quad{block: bBlock, seenCommit: bSeenCommit, commit: bCommit,
  269. meta: bBlockMeta}, nil
  270. })
  271. if subStr := tuple.wantPanic; subStr != "" {
  272. if panicErr == nil {
  273. t.Errorf("#%d: want a non-nil panic", i)
  274. } else if got := fmt.Sprintf("%#v", panicErr); !strings.Contains(got, subStr) {
  275. t.Errorf("#%d:\n\tgotErr: %q\nwant substring: %q", i, got, subStr)
  276. }
  277. continue
  278. }
  279. if tuple.wantErr {
  280. if err == nil {
  281. t.Errorf("#%d: got nil error", i)
  282. }
  283. continue
  284. }
  285. assert.Nil(t, panicErr, "#%d: unexpected panic", i)
  286. assert.Nil(t, err, "#%d: expecting a non-nil error", i)
  287. qua, ok := res.(*quad)
  288. if !ok || qua == nil {
  289. t.Errorf("#%d: got nil quad back; gotType=%T", i, res)
  290. continue
  291. }
  292. if tuple.eraseSeenCommitInDB {
  293. assert.Nil(t, qua.seenCommit,
  294. "erased the seenCommit in the DB hence we should get back a nil seenCommit")
  295. }
  296. if tuple.eraseCommitInDB {
  297. assert.Nil(t, qua.commit,
  298. "erased the commit in the DB hence we should get back a nil commit")
  299. }
  300. }
  301. }
  302. func TestLoadBlockPart(t *testing.T) {
  303. bs, db := freshBlockStore()
  304. height, index := int64(10), 1
  305. loadPart := func() (interface{}, error) {
  306. part := bs.LoadBlockPart(height, index)
  307. return part, nil
  308. }
  309. // Initially no contents.
  310. // 1. Requesting for a non-existent block shouldn't fail
  311. res, _, panicErr := doFn(loadPart)
  312. require.Nil(t, panicErr, "a non-existent block part shouldn't cause a panic")
  313. require.Nil(t, res, "a non-existent block part should return nil")
  314. // 2. Next save a corrupted block then try to load it
  315. err := db.Set(calcBlockPartKey(height, index), []byte("Tendermint"))
  316. require.NoError(t, err)
  317. res, _, panicErr = doFn(loadPart)
  318. require.NotNil(t, panicErr, "expecting a non-nil panic")
  319. require.Contains(t, panicErr.Error(), "unmarshal to types.Part failed")
  320. // 3. A good block serialized and saved to the DB should be retrievable
  321. err = db.Set(calcBlockPartKey(height, index), cdc.MustMarshalBinaryBare(part1))
  322. require.NoError(t, err)
  323. gotPart, _, panicErr := doFn(loadPart)
  324. require.Nil(t, panicErr, "an existent and proper block should not panic")
  325. require.Nil(t, res, "a properly saved block should return a proper block")
  326. require.Equal(t, gotPart.(*types.Part), part1,
  327. "expecting successful retrieval of previously saved block")
  328. }
  329. func TestPruneBlocks(t *testing.T) {
  330. config := cfg.ResetTestRoot("blockchain_reactor_test")
  331. defer os.RemoveAll(config.RootDir)
  332. state, err := sm.LoadStateFromDBOrGenesisFile(dbm.NewMemDB(), config.GenesisFile())
  333. require.NoError(t, err)
  334. db := dbm.NewMemDB()
  335. bs := NewBlockStore(db)
  336. assert.EqualValues(t, 0, bs.Base())
  337. assert.EqualValues(t, 0, bs.Height())
  338. assert.EqualValues(t, 0, bs.Size())
  339. // pruning an empty store should error, even when pruning to 0
  340. _, err = bs.PruneBlocks(1)
  341. require.Error(t, err)
  342. _, err = bs.PruneBlocks(0)
  343. require.Error(t, err)
  344. // make more than 1000 blocks, to test batch deletions
  345. for h := int64(1); h <= 1500; h++ {
  346. block := makeBlock(h, state, new(types.Commit))
  347. partSet := block.MakePartSet(2)
  348. seenCommit := makeTestCommit(h, tmtime.Now())
  349. bs.SaveBlock(block, partSet, seenCommit)
  350. }
  351. assert.EqualValues(t, 1, bs.Base())
  352. assert.EqualValues(t, 1500, bs.Height())
  353. assert.EqualValues(t, 1500, bs.Size())
  354. prunedBlock := bs.LoadBlock(1199)
  355. // Check that basic pruning works
  356. pruned, err := bs.PruneBlocks(1200)
  357. require.NoError(t, err)
  358. assert.EqualValues(t, 1199, pruned)
  359. assert.EqualValues(t, 1200, bs.Base())
  360. assert.EqualValues(t, 1500, bs.Height())
  361. assert.EqualValues(t, 301, bs.Size())
  362. assert.EqualValues(t, BlockStoreStateJSON{
  363. Base: 1200,
  364. Height: 1500,
  365. }, LoadBlockStoreStateJSON(db))
  366. require.NotNil(t, bs.LoadBlock(1200))
  367. require.Nil(t, bs.LoadBlock(1199))
  368. require.Nil(t, bs.LoadBlockByHash(prunedBlock.Hash()))
  369. require.Nil(t, bs.LoadBlockCommit(1199))
  370. require.Nil(t, bs.LoadBlockMeta(1199))
  371. require.Nil(t, bs.LoadBlockPart(1199, 1))
  372. for i := int64(1); i < 1200; i++ {
  373. require.Nil(t, bs.LoadBlock(i))
  374. }
  375. for i := int64(1200); i <= 1500; i++ {
  376. require.NotNil(t, bs.LoadBlock(i))
  377. }
  378. // Pruning below the current base should error
  379. _, err = bs.PruneBlocks(1199)
  380. require.Error(t, err)
  381. // Pruning to the current base should work
  382. pruned, err = bs.PruneBlocks(1200)
  383. require.NoError(t, err)
  384. assert.EqualValues(t, 0, pruned)
  385. // Pruning again should work
  386. pruned, err = bs.PruneBlocks(1300)
  387. require.NoError(t, err)
  388. assert.EqualValues(t, 100, pruned)
  389. assert.EqualValues(t, 1300, bs.Base())
  390. // Pruning beyond the current height should error
  391. _, err = bs.PruneBlocks(1501)
  392. require.Error(t, err)
  393. // Pruning to the current height should work
  394. pruned, err = bs.PruneBlocks(1500)
  395. require.NoError(t, err)
  396. assert.EqualValues(t, 200, pruned)
  397. assert.Nil(t, bs.LoadBlock(1499))
  398. assert.NotNil(t, bs.LoadBlock(1500))
  399. assert.Nil(t, bs.LoadBlock(1501))
  400. }
  401. func TestLoadBlockMeta(t *testing.T) {
  402. bs, db := freshBlockStore()
  403. height := int64(10)
  404. loadMeta := func() (interface{}, error) {
  405. meta := bs.LoadBlockMeta(height)
  406. return meta, nil
  407. }
  408. // Initially no contents.
  409. // 1. Requesting for a non-existent blockMeta shouldn't fail
  410. res, _, panicErr := doFn(loadMeta)
  411. require.Nil(t, panicErr, "a non-existent blockMeta shouldn't cause a panic")
  412. require.Nil(t, res, "a non-existent blockMeta should return nil")
  413. // 2. Next save a corrupted blockMeta then try to load it
  414. err := db.Set(calcBlockMetaKey(height), []byte("Tendermint-Meta"))
  415. require.NoError(t, err)
  416. res, _, panicErr = doFn(loadMeta)
  417. require.NotNil(t, panicErr, "expecting a non-nil panic")
  418. require.Contains(t, panicErr.Error(), "unmarshal to types.BlockMeta")
  419. // 3. A good blockMeta serialized and saved to the DB should be retrievable
  420. meta := &types.BlockMeta{}
  421. err = db.Set(calcBlockMetaKey(height), cdc.MustMarshalBinaryBare(meta))
  422. require.NoError(t, err)
  423. gotMeta, _, panicErr := doFn(loadMeta)
  424. require.Nil(t, panicErr, "an existent and proper block should not panic")
  425. require.Nil(t, res, "a properly saved blockMeta should return a proper blocMeta ")
  426. require.Equal(t, cdc.MustMarshalBinaryBare(meta), cdc.MustMarshalBinaryBare(gotMeta),
  427. "expecting successful retrieval of previously saved blockMeta")
  428. }
  429. func TestBlockFetchAtHeight(t *testing.T) {
  430. state, bs, cleanup := makeStateAndBlockStore(log.NewTMLogger(new(bytes.Buffer)))
  431. defer cleanup()
  432. require.Equal(t, bs.Height(), int64(0), "initially the height should be zero")
  433. block := makeBlock(bs.Height()+1, state, new(types.Commit))
  434. partSet := block.MakePartSet(2)
  435. seenCommit := makeTestCommit(10, tmtime.Now())
  436. bs.SaveBlock(block, partSet, seenCommit)
  437. require.Equal(t, bs.Height(), block.Header.Height, "expecting the new height to be changed")
  438. blockAtHeight := bs.LoadBlock(bs.Height())
  439. bz1 := cdc.MustMarshalBinaryBare(block)
  440. bz2 := cdc.MustMarshalBinaryBare(blockAtHeight)
  441. require.Equal(t, bz1, bz2)
  442. require.Equal(t, block.Hash(), blockAtHeight.Hash(),
  443. "expecting a successful load of the last saved block")
  444. blockAtHeightPlus1 := bs.LoadBlock(bs.Height() + 1)
  445. require.Nil(t, blockAtHeightPlus1, "expecting an unsuccessful load of Height()+1")
  446. blockAtHeightPlus2 := bs.LoadBlock(bs.Height() + 2)
  447. require.Nil(t, blockAtHeightPlus2, "expecting an unsuccessful load of Height()+2")
  448. }
  449. func doFn(fn func() (interface{}, error)) (res interface{}, err error, panicErr error) {
  450. defer func() {
  451. if r := recover(); r != nil {
  452. switch e := r.(type) {
  453. case error:
  454. panicErr = e
  455. case string:
  456. panicErr = fmt.Errorf("%s", e)
  457. default:
  458. if st, ok := r.(fmt.Stringer); ok {
  459. panicErr = fmt.Errorf("%s", st)
  460. } else {
  461. panicErr = fmt.Errorf("%s", debug.Stack())
  462. }
  463. }
  464. }
  465. }()
  466. res, err = fn()
  467. return res, err, panicErr
  468. }
  469. func newBlock(hdr types.Header, lastCommit *types.Commit) *types.Block {
  470. return &types.Block{
  471. Header: hdr,
  472. LastCommit: lastCommit,
  473. }
  474. }