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.

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