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.

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