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.

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