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.

579 lines
17 KiB

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