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.

558 lines
17 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
  1. package store
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os"
  6. "runtime/debug"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/pkg/errors"
  11. "github.com/stretchr/testify/assert"
  12. "github.com/stretchr/testify/require"
  13. db "github.com/tendermint/tm-db"
  14. dbm "github.com/tendermint/tm-db"
  15. cfg "github.com/tendermint/tendermint/config"
  16. "github.com/tendermint/tendermint/libs/log"
  17. sm "github.com/tendermint/tendermint/state"
  18. "github.com/tendermint/tendermint/types"
  19. tmtime "github.com/tendermint/tendermint/types/time"
  20. )
  21. // A cleanupFunc cleans up any config / test files created for a particular
  22. // test.
  23. type cleanupFunc func()
  24. // make a Commit with a single vote containing just the height and a timestamp
  25. func makeTestCommit(height int64, timestamp time.Time) *types.Commit {
  26. commitSigs := []types.CommitSig{{
  27. BlockIDFlag: types.BlockIDFlagCommit,
  28. ValidatorAddress: []byte("ValidatorAddress"),
  29. Timestamp: timestamp,
  30. Signature: []byte("Signature"),
  31. }}
  32. return types.NewCommit(height, 0, types.BlockID{}, commitSigs)
  33. }
  34. func makeTxs(height int64) (txs []types.Tx) {
  35. for i := 0; i < 10; i++ {
  36. txs = append(txs, types.Tx([]byte{byte(height), byte(i)}))
  37. }
  38. return txs
  39. }
  40. func makeBlock(height int64, state sm.State, lastCommit *types.Commit) *types.Block {
  41. block, _ := state.MakeBlock(height, makeTxs(height), lastCommit, nil, state.Validators.GetProposer().Address)
  42. return block
  43. }
  44. func makeStateAndBlockStore(logger log.Logger) (sm.State, *BlockStore, cleanupFunc) {
  45. config := cfg.ResetTestRoot("blockchain_reactor_test")
  46. // blockDB := dbm.NewDebugDB("blockDB", dbm.NewMemDB())
  47. // stateDB := dbm.NewDebugDB("stateDB", dbm.NewMemDB())
  48. blockDB := dbm.NewMemDB()
  49. stateDB := dbm.NewMemDB()
  50. state, err := sm.LoadStateFromDBOrGenesisFile(stateDB, config.GenesisFile())
  51. if err != nil {
  52. panic(errors.Wrap(err, "error constructing state from genesis file"))
  53. }
  54. return state, NewBlockStore(blockDB), func() { os.RemoveAll(config.RootDir) }
  55. }
  56. func TestLoadBlockStoreStateJSON(t *testing.T) {
  57. db := db.NewMemDB()
  58. bsj := &BlockStoreStateJSON{Base: 100, Height: 1000}
  59. bsj.Save(db)
  60. retrBSJ := LoadBlockStoreStateJSON(db)
  61. assert.Equal(t, *bsj, retrBSJ, "expected the retrieved DBs to match")
  62. }
  63. func TestLoadBlockStoreStateJSON_Empty(t *testing.T) {
  64. db := db.NewMemDB()
  65. bsj := &BlockStoreStateJSON{}
  66. bsj.Save(db)
  67. retrBSJ := LoadBlockStoreStateJSON(db)
  68. assert.Equal(t, BlockStoreStateJSON{}, retrBSJ, "expected the retrieved DBs to match")
  69. }
  70. func TestLoadBlockStoreStateJSON_NoBase(t *testing.T) {
  71. db := db.NewMemDB()
  72. bsj := &BlockStoreStateJSON{Height: 1000}
  73. bsj.Save(db)
  74. retrBSJ := LoadBlockStoreStateJSON(db)
  75. assert.Equal(t, BlockStoreStateJSON{Base: 1, Height: 1000}, retrBSJ, "expected the retrieved DBs to match")
  76. }
  77. func TestNewBlockStore(t *testing.T) {
  78. db := db.NewMemDB()
  79. err := db.Set(blockStoreKey, []byte(`{"base": "100", "height": "10000"}`))
  80. require.NoError(t, err)
  81. bs := NewBlockStore(db)
  82. require.Equal(t, int64(100), bs.Base(), "failed to properly parse blockstore")
  83. require.Equal(t, int64(10000), bs.Height(), "failed to properly parse blockstore")
  84. panicCausers := []struct {
  85. data []byte
  86. wantErr string
  87. }{
  88. {[]byte("artful-doger"), "not unmarshal bytes"},
  89. {[]byte(" "), "unmarshal bytes"},
  90. }
  91. for i, tt := range panicCausers {
  92. tt := tt
  93. // Expecting a panic here on trying to parse an invalid blockStore
  94. _, _, panicErr := doFn(func() (interface{}, error) {
  95. err := db.Set(blockStoreKey, tt.data)
  96. require.NoError(t, err)
  97. _ = NewBlockStore(db)
  98. return nil, nil
  99. })
  100. require.NotNil(t, panicErr, "#%d panicCauser: %q expected a panic", i, tt.data)
  101. assert.Contains(t, fmt.Sprintf("%#v", panicErr), tt.wantErr, "#%d data: %q", i, tt.data)
  102. }
  103. err = db.Set(blockStoreKey, nil)
  104. require.NoError(t, err)
  105. bs = NewBlockStore(db)
  106. assert.Equal(t, bs.Height(), int64(0), "expecting nil bytes to be unmarshaled alright")
  107. }
  108. func freshBlockStore() (*BlockStore, db.DB) {
  109. db := db.NewMemDB()
  110. return NewBlockStore(db), db
  111. }
  112. var (
  113. state sm.State
  114. block *types.Block
  115. partSet *types.PartSet
  116. part1 *types.Part
  117. part2 *types.Part
  118. seenCommit1 *types.Commit
  119. )
  120. func TestMain(m *testing.M) {
  121. var cleanup cleanupFunc
  122. state, _, cleanup = makeStateAndBlockStore(log.NewTMLogger(new(bytes.Buffer)))
  123. block = makeBlock(1, state, new(types.Commit))
  124. partSet = block.MakePartSet(2)
  125. part1 = partSet.GetPart(0)
  126. part2 = partSet.GetPart(1)
  127. seenCommit1 = makeTestCommit(10, tmtime.Now())
  128. code := m.Run()
  129. cleanup()
  130. os.Exit(code)
  131. }
  132. // TODO: This test should be simplified ...
  133. func TestBlockStoreSaveLoadBlock(t *testing.T) {
  134. state, bs, cleanup := makeStateAndBlockStore(log.NewTMLogger(new(bytes.Buffer)))
  135. defer cleanup()
  136. require.Equal(t, bs.Base(), int64(0), "initially the base should be zero")
  137. require.Equal(t, bs.Height(), int64(0), "initially the height should be zero")
  138. // check there are no blocks at various heights
  139. noBlockHeights := []int64{0, -1, 100, 1000, 2}
  140. for i, height := range noBlockHeights {
  141. if g := bs.LoadBlock(height); g != nil {
  142. t.Errorf("#%d: height(%d) got a block; want nil", i, height)
  143. }
  144. }
  145. // save a block
  146. block := makeBlock(bs.Height()+1, state, new(types.Commit))
  147. validPartSet := block.MakePartSet(2)
  148. seenCommit := makeTestCommit(10, tmtime.Now())
  149. bs.SaveBlock(block, partSet, seenCommit)
  150. require.EqualValues(t, 1, bs.Base(), "expecting the new height to be changed")
  151. require.EqualValues(t, block.Header.Height, bs.Height(), "expecting the new height to be changed")
  152. incompletePartSet := types.NewPartSetFromHeader(types.PartSetHeader{Total: 2})
  153. uncontiguousPartSet := types.NewPartSetFromHeader(types.PartSetHeader{Total: 0})
  154. uncontiguousPartSet.AddPart(part2)
  155. header1 := types.Header{
  156. Height: 1,
  157. ChainID: "block_test",
  158. Time: tmtime.Now(),
  159. }
  160. // End of setup, test data
  161. commitAtH10 := makeTestCommit(10, tmtime.Now())
  162. tuples := []struct {
  163. block *types.Block
  164. parts *types.PartSet
  165. seenCommit *types.Commit
  166. wantPanic string
  167. wantErr bool
  168. corruptBlockInDB bool
  169. corruptCommitInDB bool
  170. corruptSeenCommitInDB bool
  171. eraseCommitInDB bool
  172. eraseSeenCommitInDB bool
  173. }{
  174. {
  175. block: newBlock(header1, commitAtH10),
  176. parts: validPartSet,
  177. seenCommit: seenCommit1,
  178. },
  179. {
  180. block: nil,
  181. wantPanic: "only save a non-nil block",
  182. },
  183. {
  184. block: newBlock( // New block at height 5 in empty block store is fine
  185. types.Header{Height: 5, ChainID: "block_test", Time: tmtime.Now()},
  186. makeTestCommit(5, tmtime.Now()),
  187. ),
  188. parts: validPartSet,
  189. seenCommit: makeTestCommit(5, tmtime.Now()),
  190. },
  191. {
  192. block: newBlock(header1, commitAtH10),
  193. parts: incompletePartSet,
  194. wantPanic: "only save complete block", // incomplete parts
  195. },
  196. {
  197. block: newBlock(header1, commitAtH10),
  198. parts: validPartSet,
  199. seenCommit: seenCommit1,
  200. corruptCommitInDB: true, // Corrupt the DB's commit entry
  201. wantPanic: "unmarshal to types.Commit failed",
  202. },
  203. {
  204. block: newBlock(header1, commitAtH10),
  205. parts: validPartSet,
  206. seenCommit: seenCommit1,
  207. wantPanic: "unmarshal to types.BlockMeta failed",
  208. corruptBlockInDB: true, // Corrupt the DB's block entry
  209. },
  210. {
  211. block: newBlock(header1, commitAtH10),
  212. parts: validPartSet,
  213. seenCommit: seenCommit1,
  214. // Expecting no error and we want a nil back
  215. eraseSeenCommitInDB: true,
  216. },
  217. {
  218. block: newBlock(header1, commitAtH10),
  219. parts: validPartSet,
  220. seenCommit: seenCommit1,
  221. corruptSeenCommitInDB: true,
  222. wantPanic: "unmarshal to types.Commit failed",
  223. },
  224. {
  225. block: newBlock(header1, commitAtH10),
  226. parts: validPartSet,
  227. seenCommit: seenCommit1,
  228. // Expecting no error and we want a nil back
  229. eraseCommitInDB: true,
  230. },
  231. }
  232. type quad struct {
  233. block *types.Block
  234. commit *types.Commit
  235. meta *types.BlockMeta
  236. seenCommit *types.Commit
  237. }
  238. for i, tuple := range tuples {
  239. tuple := tuple
  240. bs, db := freshBlockStore()
  241. // SaveBlock
  242. res, err, panicErr := doFn(func() (interface{}, error) {
  243. bs.SaveBlock(tuple.block, tuple.parts, tuple.seenCommit)
  244. if tuple.block == nil {
  245. return nil, nil
  246. }
  247. if tuple.corruptBlockInDB {
  248. err := db.Set(calcBlockMetaKey(tuple.block.Height), []byte("block-bogus"))
  249. require.NoError(t, err)
  250. }
  251. bBlock := bs.LoadBlock(tuple.block.Height)
  252. bBlockMeta := bs.LoadBlockMeta(tuple.block.Height)
  253. if tuple.eraseSeenCommitInDB {
  254. db.Delete(calcSeenCommitKey(tuple.block.Height))
  255. }
  256. if tuple.corruptSeenCommitInDB {
  257. err := db.Set(calcSeenCommitKey(tuple.block.Height), []byte("bogus-seen-commit"))
  258. require.NoError(t, err)
  259. }
  260. bSeenCommit := bs.LoadSeenCommit(tuple.block.Height)
  261. commitHeight := tuple.block.Height - 1
  262. if tuple.eraseCommitInDB {
  263. db.Delete(calcBlockCommitKey(commitHeight))
  264. }
  265. if tuple.corruptCommitInDB {
  266. err := db.Set(calcBlockCommitKey(commitHeight), []byte("foo-bogus"))
  267. require.NoError(t, err)
  268. }
  269. bCommit := bs.LoadBlockCommit(commitHeight)
  270. return &quad{block: bBlock, seenCommit: bSeenCommit, commit: bCommit,
  271. meta: bBlockMeta}, nil
  272. })
  273. if subStr := tuple.wantPanic; subStr != "" {
  274. if panicErr == nil {
  275. t.Errorf("#%d: want a non-nil panic", i)
  276. } else if got := fmt.Sprintf("%#v", panicErr); !strings.Contains(got, subStr) {
  277. t.Errorf("#%d:\n\tgotErr: %q\nwant substring: %q", i, got, subStr)
  278. }
  279. continue
  280. }
  281. if tuple.wantErr {
  282. if err == nil {
  283. t.Errorf("#%d: got nil error", i)
  284. }
  285. continue
  286. }
  287. assert.Nil(t, panicErr, "#%d: unexpected panic", i)
  288. assert.Nil(t, err, "#%d: expecting a non-nil error", i)
  289. qua, ok := res.(*quad)
  290. if !ok || qua == nil {
  291. t.Errorf("#%d: got nil quad back; gotType=%T", i, res)
  292. continue
  293. }
  294. if tuple.eraseSeenCommitInDB {
  295. assert.Nil(t, qua.seenCommit,
  296. "erased the seenCommit in the DB hence we should get back a nil seenCommit")
  297. }
  298. if tuple.eraseCommitInDB {
  299. assert.Nil(t, qua.commit,
  300. "erased the commit in the DB hence we should get back a nil commit")
  301. }
  302. }
  303. }
  304. func TestLoadBlockPart(t *testing.T) {
  305. bs, db := freshBlockStore()
  306. height, index := int64(10), 1
  307. loadPart := func() (interface{}, error) {
  308. part := bs.LoadBlockPart(height, index)
  309. return part, nil
  310. }
  311. // Initially no contents.
  312. // 1. Requesting for a non-existent block shouldn't fail
  313. res, _, panicErr := doFn(loadPart)
  314. require.Nil(t, panicErr, "a non-existent block part shouldn't cause a panic")
  315. require.Nil(t, res, "a non-existent block part should return nil")
  316. // 2. Next save a corrupted block then try to load it
  317. err := db.Set(calcBlockPartKey(height, index), []byte("Tendermint"))
  318. require.NoError(t, err)
  319. res, _, panicErr = doFn(loadPart)
  320. require.NotNil(t, panicErr, "expecting a non-nil panic")
  321. require.Contains(t, panicErr.Error(), "unmarshal to types.Part failed")
  322. // 3. A good block serialized and saved to the DB should be retrievable
  323. err = db.Set(calcBlockPartKey(height, index), cdc.MustMarshalBinaryBare(part1))
  324. require.NoError(t, err)
  325. gotPart, _, panicErr := doFn(loadPart)
  326. require.Nil(t, panicErr, "an existent and proper block should not panic")
  327. require.Nil(t, res, "a properly saved block should return a proper block")
  328. require.Equal(t, gotPart.(*types.Part), part1,
  329. "expecting successful retrieval of previously saved block")
  330. }
  331. func TestPruneBlocks(t *testing.T) {
  332. config := cfg.ResetTestRoot("blockchain_reactor_test")
  333. defer os.RemoveAll(config.RootDir)
  334. state, err := sm.LoadStateFromDBOrGenesisFile(dbm.NewMemDB(), config.GenesisFile())
  335. require.NoError(t, err)
  336. db := dbm.NewMemDB()
  337. bs := NewBlockStore(db)
  338. assert.EqualValues(t, 0, bs.Base())
  339. assert.EqualValues(t, 0, bs.Height())
  340. assert.EqualValues(t, 0, bs.Size())
  341. // pruning an empty store should error, even when pruning to 0
  342. _, err = bs.PruneBlocks(1)
  343. require.Error(t, err)
  344. _, err = bs.PruneBlocks(0)
  345. require.Error(t, err)
  346. // make more than 1000 blocks, to test batch deletions
  347. for h := int64(1); h <= 1500; h++ {
  348. block := makeBlock(h, state, new(types.Commit))
  349. partSet := block.MakePartSet(2)
  350. seenCommit := makeTestCommit(h, tmtime.Now())
  351. bs.SaveBlock(block, partSet, seenCommit)
  352. }
  353. assert.EqualValues(t, 1, bs.Base())
  354. assert.EqualValues(t, 1500, bs.Height())
  355. assert.EqualValues(t, 1500, bs.Size())
  356. prunedBlock := bs.LoadBlock(1199)
  357. // Check that basic pruning works
  358. pruned, err := bs.PruneBlocks(1200)
  359. require.NoError(t, err)
  360. assert.EqualValues(t, 1199, pruned)
  361. assert.EqualValues(t, 1200, bs.Base())
  362. assert.EqualValues(t, 1500, bs.Height())
  363. assert.EqualValues(t, 301, bs.Size())
  364. assert.EqualValues(t, BlockStoreStateJSON{
  365. Base: 1200,
  366. Height: 1500,
  367. }, LoadBlockStoreStateJSON(db))
  368. require.NotNil(t, bs.LoadBlock(1200))
  369. require.Nil(t, bs.LoadBlock(1199))
  370. require.Nil(t, bs.LoadBlockByHash(prunedBlock.Hash()))
  371. require.Nil(t, bs.LoadBlockCommit(1199))
  372. require.Nil(t, bs.LoadBlockMeta(1199))
  373. require.Nil(t, bs.LoadBlockPart(1199, 1))
  374. for i := int64(1); i < 1200; i++ {
  375. require.Nil(t, bs.LoadBlock(i))
  376. }
  377. for i := int64(1200); i <= 1500; i++ {
  378. require.NotNil(t, bs.LoadBlock(i))
  379. }
  380. // Pruning below the current base should error
  381. _, err = bs.PruneBlocks(1199)
  382. require.Error(t, err)
  383. // Pruning to the current base should work
  384. pruned, err = bs.PruneBlocks(1200)
  385. require.NoError(t, err)
  386. assert.EqualValues(t, 0, pruned)
  387. // Pruning again should work
  388. pruned, err = bs.PruneBlocks(1300)
  389. require.NoError(t, err)
  390. assert.EqualValues(t, 100, pruned)
  391. assert.EqualValues(t, 1300, bs.Base())
  392. // Pruning beyond the current height should error
  393. _, err = bs.PruneBlocks(1501)
  394. require.Error(t, err)
  395. // Pruning to the current height should work
  396. pruned, err = bs.PruneBlocks(1500)
  397. require.NoError(t, err)
  398. assert.EqualValues(t, 200, pruned)
  399. assert.Nil(t, bs.LoadBlock(1499))
  400. assert.NotNil(t, bs.LoadBlock(1500))
  401. assert.Nil(t, bs.LoadBlock(1501))
  402. }
  403. func TestLoadBlockMeta(t *testing.T) {
  404. bs, db := freshBlockStore()
  405. height := int64(10)
  406. loadMeta := func() (interface{}, error) {
  407. meta := bs.LoadBlockMeta(height)
  408. return meta, nil
  409. }
  410. // Initially no contents.
  411. // 1. Requesting for a non-existent blockMeta shouldn't fail
  412. res, _, panicErr := doFn(loadMeta)
  413. require.Nil(t, panicErr, "a non-existent blockMeta shouldn't cause a panic")
  414. require.Nil(t, res, "a non-existent blockMeta should return nil")
  415. // 2. Next save a corrupted blockMeta then try to load it
  416. err := db.Set(calcBlockMetaKey(height), []byte("Tendermint-Meta"))
  417. require.NoError(t, err)
  418. res, _, panicErr = doFn(loadMeta)
  419. require.NotNil(t, panicErr, "expecting a non-nil panic")
  420. require.Contains(t, panicErr.Error(), "unmarshal to types.BlockMeta")
  421. // 3. A good blockMeta serialized and saved to the DB should be retrievable
  422. meta := &types.BlockMeta{}
  423. err = db.Set(calcBlockMetaKey(height), cdc.MustMarshalBinaryBare(meta))
  424. require.NoError(t, err)
  425. gotMeta, _, panicErr := doFn(loadMeta)
  426. require.Nil(t, panicErr, "an existent and proper block should not panic")
  427. require.Nil(t, res, "a properly saved blockMeta should return a proper blocMeta ")
  428. require.Equal(t, cdc.MustMarshalBinaryBare(meta), cdc.MustMarshalBinaryBare(gotMeta),
  429. "expecting successful retrieval of previously saved blockMeta")
  430. }
  431. func TestBlockFetchAtHeight(t *testing.T) {
  432. state, bs, cleanup := makeStateAndBlockStore(log.NewTMLogger(new(bytes.Buffer)))
  433. defer cleanup()
  434. require.Equal(t, bs.Height(), int64(0), "initially the height should be zero")
  435. block := makeBlock(bs.Height()+1, state, new(types.Commit))
  436. partSet := block.MakePartSet(2)
  437. seenCommit := makeTestCommit(10, tmtime.Now())
  438. bs.SaveBlock(block, partSet, seenCommit)
  439. require.Equal(t, bs.Height(), block.Header.Height, "expecting the new height to be changed")
  440. blockAtHeight := bs.LoadBlock(bs.Height())
  441. bz1 := cdc.MustMarshalBinaryBare(block)
  442. bz2 := cdc.MustMarshalBinaryBare(blockAtHeight)
  443. require.Equal(t, bz1, bz2)
  444. require.Equal(t, block.Hash(), blockAtHeight.Hash(),
  445. "expecting a successful load of the last saved block")
  446. blockAtHeightPlus1 := bs.LoadBlock(bs.Height() + 1)
  447. require.Nil(t, blockAtHeightPlus1, "expecting an unsuccessful load of Height()+1")
  448. blockAtHeightPlus2 := bs.LoadBlock(bs.Height() + 2)
  449. require.Nil(t, blockAtHeightPlus2, "expecting an unsuccessful load of Height()+2")
  450. }
  451. func doFn(fn func() (interface{}, error)) (res interface{}, err error, panicErr error) {
  452. defer func() {
  453. if r := recover(); r != nil {
  454. switch e := r.(type) {
  455. case error:
  456. panicErr = e
  457. case string:
  458. panicErr = fmt.Errorf("%s", e)
  459. default:
  460. if st, ok := r.(fmt.Stringer); ok {
  461. panicErr = fmt.Errorf("%s", st)
  462. } else {
  463. panicErr = fmt.Errorf("%s", debug.Stack())
  464. }
  465. }
  466. }
  467. }()
  468. res, err = fn()
  469. return res, err, panicErr
  470. }
  471. func newBlock(hdr types.Header, lastCommit *types.Commit) *types.Block {
  472. return &types.Block{
  473. Header: hdr,
  474. LastCommit: lastCommit,
  475. }
  476. }