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.

557 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
6 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
6 years ago
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. header2 := header1
  161. header2.Height = 4
  162. // End of setup, test data
  163. commitAtH10 := makeTestCommit(10, tmtime.Now())
  164. tuples := []struct {
  165. block *types.Block
  166. parts *types.PartSet
  167. seenCommit *types.Commit
  168. wantPanic string
  169. wantErr bool
  170. corruptBlockInDB bool
  171. corruptCommitInDB bool
  172. corruptSeenCommitInDB bool
  173. eraseCommitInDB bool
  174. eraseSeenCommitInDB bool
  175. }{
  176. {
  177. block: newBlock(header1, commitAtH10),
  178. parts: validPartSet,
  179. seenCommit: seenCommit1,
  180. },
  181. {
  182. block: nil,
  183. wantPanic: "only save a non-nil block",
  184. },
  185. {
  186. block: newBlock(header2, commitAtH10),
  187. parts: uncontiguousPartSet,
  188. wantPanic: "only save contiguous blocks", // and incomplete and uncontiguous parts
  189. },
  190. {
  191. block: newBlock(header1, commitAtH10),
  192. parts: incompletePartSet,
  193. wantPanic: "only save complete block", // incomplete parts
  194. },
  195. {
  196. block: newBlock(header1, commitAtH10),
  197. parts: validPartSet,
  198. seenCommit: seenCommit1,
  199. corruptCommitInDB: true, // Corrupt the DB's commit entry
  200. wantPanic: "unmarshal to types.Commit failed",
  201. },
  202. {
  203. block: newBlock(header1, commitAtH10),
  204. parts: validPartSet,
  205. seenCommit: seenCommit1,
  206. wantPanic: "unmarshal to types.BlockMeta failed",
  207. corruptBlockInDB: true, // Corrupt the DB's block entry
  208. },
  209. {
  210. block: newBlock(header1, commitAtH10),
  211. parts: validPartSet,
  212. seenCommit: seenCommit1,
  213. // Expecting no error and we want a nil back
  214. eraseSeenCommitInDB: true,
  215. },
  216. {
  217. block: newBlock(header1, commitAtH10),
  218. parts: validPartSet,
  219. seenCommit: seenCommit1,
  220. corruptSeenCommitInDB: true,
  221. wantPanic: "unmarshal to types.Commit failed",
  222. },
  223. {
  224. block: newBlock(header1, commitAtH10),
  225. parts: validPartSet,
  226. seenCommit: seenCommit1,
  227. // Expecting no error and we want a nil back
  228. eraseCommitInDB: true,
  229. },
  230. }
  231. type quad struct {
  232. block *types.Block
  233. commit *types.Commit
  234. meta *types.BlockMeta
  235. seenCommit *types.Commit
  236. }
  237. for i, tuple := range tuples {
  238. tuple := tuple
  239. bs, db := freshBlockStore()
  240. // SaveBlock
  241. res, err, panicErr := doFn(func() (interface{}, error) {
  242. bs.SaveBlock(tuple.block, tuple.parts, tuple.seenCommit)
  243. if tuple.block == nil {
  244. return nil, nil
  245. }
  246. if tuple.corruptBlockInDB {
  247. err := db.Set(calcBlockMetaKey(tuple.block.Height), []byte("block-bogus"))
  248. require.NoError(t, err)
  249. }
  250. bBlock := bs.LoadBlock(tuple.block.Height)
  251. bBlockMeta := bs.LoadBlockMeta(tuple.block.Height)
  252. if tuple.eraseSeenCommitInDB {
  253. db.Delete(calcSeenCommitKey(tuple.block.Height))
  254. }
  255. if tuple.corruptSeenCommitInDB {
  256. err := db.Set(calcSeenCommitKey(tuple.block.Height), []byte("bogus-seen-commit"))
  257. require.NoError(t, err)
  258. }
  259. bSeenCommit := bs.LoadSeenCommit(tuple.block.Height)
  260. commitHeight := tuple.block.Height - 1
  261. if tuple.eraseCommitInDB {
  262. db.Delete(calcBlockCommitKey(commitHeight))
  263. }
  264. if tuple.corruptCommitInDB {
  265. err := db.Set(calcBlockCommitKey(commitHeight), []byte("foo-bogus"))
  266. require.NoError(t, err)
  267. }
  268. bCommit := bs.LoadBlockCommit(commitHeight)
  269. return &quad{block: bBlock, seenCommit: bSeenCommit, commit: bCommit,
  270. meta: bBlockMeta}, nil
  271. })
  272. if subStr := tuple.wantPanic; subStr != "" {
  273. if panicErr == nil {
  274. t.Errorf("#%d: want a non-nil panic", i)
  275. } else if got := fmt.Sprintf("%#v", panicErr); !strings.Contains(got, subStr) {
  276. t.Errorf("#%d:\n\tgotErr: %q\nwant substring: %q", i, got, subStr)
  277. }
  278. continue
  279. }
  280. if tuple.wantErr {
  281. if err == nil {
  282. t.Errorf("#%d: got nil error", i)
  283. }
  284. continue
  285. }
  286. assert.Nil(t, panicErr, "#%d: unexpected panic", i)
  287. assert.Nil(t, err, "#%d: expecting a non-nil error", i)
  288. qua, ok := res.(*quad)
  289. if !ok || qua == nil {
  290. t.Errorf("#%d: got nil quad back; gotType=%T", i, res)
  291. continue
  292. }
  293. if tuple.eraseSeenCommitInDB {
  294. assert.Nil(t, qua.seenCommit,
  295. "erased the seenCommit in the DB hence we should get back a nil seenCommit")
  296. }
  297. if tuple.eraseCommitInDB {
  298. assert.Nil(t, qua.commit,
  299. "erased the commit in the DB hence we should get back a nil commit")
  300. }
  301. }
  302. }
  303. func TestLoadBlockPart(t *testing.T) {
  304. bs, db := freshBlockStore()
  305. height, index := int64(10), 1
  306. loadPart := func() (interface{}, error) {
  307. part := bs.LoadBlockPart(height, index)
  308. return part, nil
  309. }
  310. // Initially no contents.
  311. // 1. Requesting for a non-existent block shouldn't fail
  312. res, _, panicErr := doFn(loadPart)
  313. require.Nil(t, panicErr, "a non-existent block part shouldn't cause a panic")
  314. require.Nil(t, res, "a non-existent block part should return nil")
  315. // 2. Next save a corrupted block then try to load it
  316. err := db.Set(calcBlockPartKey(height, index), []byte("Tendermint"))
  317. require.NoError(t, err)
  318. res, _, panicErr = doFn(loadPart)
  319. require.NotNil(t, panicErr, "expecting a non-nil panic")
  320. require.Contains(t, panicErr.Error(), "unmarshal to types.Part failed")
  321. // 3. A good block serialized and saved to the DB should be retrievable
  322. err = db.Set(calcBlockPartKey(height, index), cdc.MustMarshalBinaryBare(part1))
  323. require.NoError(t, err)
  324. gotPart, _, panicErr := doFn(loadPart)
  325. require.Nil(t, panicErr, "an existent and proper block should not panic")
  326. require.Nil(t, res, "a properly saved block should return a proper block")
  327. require.Equal(t, gotPart.(*types.Part), part1,
  328. "expecting successful retrieval of previously saved block")
  329. }
  330. func TestPruneBlocks(t *testing.T) {
  331. config := cfg.ResetTestRoot("blockchain_reactor_test")
  332. defer os.RemoveAll(config.RootDir)
  333. state, err := sm.LoadStateFromDBOrGenesisFile(dbm.NewMemDB(), config.GenesisFile())
  334. require.NoError(t, err)
  335. db := dbm.NewMemDB()
  336. bs := NewBlockStore(db)
  337. assert.EqualValues(t, 0, bs.Base())
  338. assert.EqualValues(t, 0, bs.Height())
  339. assert.EqualValues(t, 0, bs.Size())
  340. // pruning an empty store should error, even when pruning to 0
  341. _, err = bs.PruneBlocks(1)
  342. require.Error(t, err)
  343. _, err = bs.PruneBlocks(0)
  344. require.Error(t, err)
  345. // make more than 1000 blocks, to test batch deletions
  346. for h := int64(1); h <= 1500; h++ {
  347. block := makeBlock(h, state, new(types.Commit))
  348. partSet := block.MakePartSet(2)
  349. seenCommit := makeTestCommit(h, tmtime.Now())
  350. bs.SaveBlock(block, partSet, seenCommit)
  351. }
  352. assert.EqualValues(t, 1, bs.Base())
  353. assert.EqualValues(t, 1500, bs.Height())
  354. assert.EqualValues(t, 1500, bs.Size())
  355. prunedBlock := bs.LoadBlock(1199)
  356. // Check that basic pruning works
  357. pruned, err := bs.PruneBlocks(1200)
  358. require.NoError(t, err)
  359. assert.EqualValues(t, 1199, pruned)
  360. assert.EqualValues(t, 1200, bs.Base())
  361. assert.EqualValues(t, 1500, bs.Height())
  362. assert.EqualValues(t, 301, bs.Size())
  363. assert.EqualValues(t, BlockStoreStateJSON{
  364. Base: 1200,
  365. Height: 1500,
  366. }, LoadBlockStoreStateJSON(db))
  367. require.NotNil(t, bs.LoadBlock(1200))
  368. require.Nil(t, bs.LoadBlock(1199))
  369. require.Nil(t, bs.LoadBlockByHash(prunedBlock.Hash()))
  370. require.Nil(t, bs.LoadBlockCommit(1199))
  371. require.Nil(t, bs.LoadBlockMeta(1199))
  372. require.Nil(t, bs.LoadBlockPart(1199, 1))
  373. for i := int64(1); i < 1200; i++ {
  374. require.Nil(t, bs.LoadBlock(i))
  375. }
  376. for i := int64(1200); i <= 1500; i++ {
  377. require.NotNil(t, bs.LoadBlock(i))
  378. }
  379. // Pruning below the current base should error
  380. _, err = bs.PruneBlocks(1199)
  381. require.Error(t, err)
  382. // Pruning to the current base should work
  383. pruned, err = bs.PruneBlocks(1200)
  384. require.NoError(t, err)
  385. assert.EqualValues(t, 0, pruned)
  386. // Pruning again should work
  387. pruned, err = bs.PruneBlocks(1300)
  388. require.NoError(t, err)
  389. assert.EqualValues(t, 100, pruned)
  390. assert.EqualValues(t, 1300, bs.Base())
  391. // Pruning beyond the current height should error
  392. _, err = bs.PruneBlocks(1501)
  393. require.Error(t, err)
  394. // Pruning to the current height should work
  395. pruned, err = bs.PruneBlocks(1500)
  396. require.NoError(t, err)
  397. assert.EqualValues(t, 200, pruned)
  398. assert.Nil(t, bs.LoadBlock(1499))
  399. assert.NotNil(t, bs.LoadBlock(1500))
  400. assert.Nil(t, bs.LoadBlock(1501))
  401. }
  402. func TestLoadBlockMeta(t *testing.T) {
  403. bs, db := freshBlockStore()
  404. height := int64(10)
  405. loadMeta := func() (interface{}, error) {
  406. meta := bs.LoadBlockMeta(height)
  407. return meta, nil
  408. }
  409. // Initially no contents.
  410. // 1. Requesting for a non-existent blockMeta shouldn't fail
  411. res, _, panicErr := doFn(loadMeta)
  412. require.Nil(t, panicErr, "a non-existent blockMeta shouldn't cause a panic")
  413. require.Nil(t, res, "a non-existent blockMeta should return nil")
  414. // 2. Next save a corrupted blockMeta then try to load it
  415. err := db.Set(calcBlockMetaKey(height), []byte("Tendermint-Meta"))
  416. require.NoError(t, err)
  417. res, _, panicErr = doFn(loadMeta)
  418. require.NotNil(t, panicErr, "expecting a non-nil panic")
  419. require.Contains(t, panicErr.Error(), "unmarshal to types.BlockMeta")
  420. // 3. A good blockMeta serialized and saved to the DB should be retrievable
  421. meta := &types.BlockMeta{}
  422. err = db.Set(calcBlockMetaKey(height), cdc.MustMarshalBinaryBare(meta))
  423. require.NoError(t, err)
  424. gotMeta, _, panicErr := doFn(loadMeta)
  425. require.Nil(t, panicErr, "an existent and proper block should not panic")
  426. require.Nil(t, res, "a properly saved blockMeta should return a proper blocMeta ")
  427. require.Equal(t, cdc.MustMarshalBinaryBare(meta), cdc.MustMarshalBinaryBare(gotMeta),
  428. "expecting successful retrieval of previously saved blockMeta")
  429. }
  430. func TestBlockFetchAtHeight(t *testing.T) {
  431. state, bs, cleanup := makeStateAndBlockStore(log.NewTMLogger(new(bytes.Buffer)))
  432. defer cleanup()
  433. require.Equal(t, bs.Height(), int64(0), "initially the height should be zero")
  434. block := makeBlock(bs.Height()+1, state, new(types.Commit))
  435. partSet := block.MakePartSet(2)
  436. seenCommit := makeTestCommit(10, tmtime.Now())
  437. bs.SaveBlock(block, partSet, seenCommit)
  438. require.Equal(t, bs.Height(), block.Header.Height, "expecting the new height to be changed")
  439. blockAtHeight := bs.LoadBlock(bs.Height())
  440. bz1 := cdc.MustMarshalBinaryBare(block)
  441. bz2 := cdc.MustMarshalBinaryBare(blockAtHeight)
  442. require.Equal(t, bz1, bz2)
  443. require.Equal(t, block.Hash(), blockAtHeight.Hash(),
  444. "expecting a successful load of the last saved block")
  445. blockAtHeightPlus1 := bs.LoadBlock(bs.Height() + 1)
  446. require.Nil(t, blockAtHeightPlus1, "expecting an unsuccessful load of Height()+1")
  447. blockAtHeightPlus2 := bs.LoadBlock(bs.Height() + 2)
  448. require.Nil(t, blockAtHeightPlus2, "expecting an unsuccessful load of Height()+2")
  449. }
  450. func doFn(fn func() (interface{}, error)) (res interface{}, err error, panicErr error) {
  451. defer func() {
  452. if r := recover(); r != nil {
  453. switch e := r.(type) {
  454. case error:
  455. panicErr = e
  456. case string:
  457. panicErr = fmt.Errorf("%s", e)
  458. default:
  459. if st, ok := r.(fmt.Stringer); ok {
  460. panicErr = fmt.Errorf("%s", st)
  461. } else {
  462. panicErr = fmt.Errorf("%s", debug.Stack())
  463. }
  464. }
  465. }
  466. }()
  467. res, err = fn()
  468. return res, err, panicErr
  469. }
  470. func newBlock(hdr types.Header, lastCommit *types.Commit) *types.Block {
  471. return &types.Block{
  472. Header: hdr,
  473. LastCommit: lastCommit,
  474. }
  475. }