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.

572 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
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/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/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(""), PartsHeader: 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, nil)
  107. require.NoError(t, err)
  108. bs = NewBlockStore(db)
  109. assert.Equal(t, bs.Height(), int64(0), "expecting nil 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. uncontiguousPartSet.AddPart(part2)
  158. header1 := types.Header{
  159. Height: 1,
  160. ChainID: "block_test",
  161. Time: tmtime.Now(),
  162. ProposerAddress: tmrand.Bytes(crypto.AddressSize),
  163. }
  164. // End of setup, test data
  165. commitAtH10 := makeTestCommit(10, tmtime.Now())
  166. tuples := []struct {
  167. block *types.Block
  168. parts *types.PartSet
  169. seenCommit *types.Commit
  170. wantPanic string
  171. wantErr bool
  172. corruptBlockInDB bool
  173. corruptCommitInDB bool
  174. corruptSeenCommitInDB bool
  175. eraseCommitInDB bool
  176. eraseSeenCommitInDB bool
  177. }{
  178. {
  179. block: newBlock(header1, commitAtH10),
  180. parts: validPartSet,
  181. seenCommit: seenCommit1,
  182. },
  183. {
  184. block: nil,
  185. wantPanic: "only save a non-nil block",
  186. },
  187. {
  188. block: newBlock( // New block at height 5 in empty block store is fine
  189. types.Header{
  190. Height: 5,
  191. ChainID: "block_test",
  192. Time: tmtime.Now(),
  193. ProposerAddress: tmrand.Bytes(crypto.AddressSize)},
  194. makeTestCommit(5, tmtime.Now()),
  195. ),
  196. parts: validPartSet,
  197. seenCommit: makeTestCommit(5, tmtime.Now()),
  198. },
  199. {
  200. block: newBlock(header1, commitAtH10),
  201. parts: incompletePartSet,
  202. wantPanic: "only save complete block", // incomplete parts
  203. },
  204. {
  205. block: newBlock(header1, commitAtH10),
  206. parts: validPartSet,
  207. seenCommit: seenCommit1,
  208. corruptCommitInDB: true, // Corrupt the DB's commit entry
  209. wantPanic: "error reading block commit",
  210. },
  211. {
  212. block: newBlock(header1, commitAtH10),
  213. parts: validPartSet,
  214. seenCommit: seenCommit1,
  215. wantPanic: "unmarshal to tmproto.BlockMeta",
  216. corruptBlockInDB: true, // Corrupt the DB's block entry
  217. },
  218. {
  219. block: newBlock(header1, commitAtH10),
  220. parts: validPartSet,
  221. seenCommit: seenCommit1,
  222. // Expecting no error and we want a nil back
  223. eraseSeenCommitInDB: true,
  224. },
  225. {
  226. block: newBlock(header1, commitAtH10),
  227. parts: validPartSet,
  228. seenCommit: seenCommit1,
  229. corruptSeenCommitInDB: true,
  230. wantPanic: "error reading block seen commit",
  231. },
  232. {
  233. block: newBlock(header1, commitAtH10),
  234. parts: validPartSet,
  235. seenCommit: seenCommit1,
  236. // Expecting no error and we want a nil back
  237. eraseCommitInDB: true,
  238. },
  239. }
  240. type quad struct {
  241. block *types.Block
  242. commit *types.Commit
  243. meta *types.BlockMeta
  244. seenCommit *types.Commit
  245. }
  246. for i, tuple := range tuples {
  247. tuple := tuple
  248. bs, db := freshBlockStore()
  249. // SaveBlock
  250. res, err, panicErr := doFn(func() (interface{}, error) {
  251. bs.SaveBlock(tuple.block, tuple.parts, tuple.seenCommit)
  252. if tuple.block == nil {
  253. return nil, nil
  254. }
  255. if tuple.corruptBlockInDB {
  256. err := db.Set(calcBlockMetaKey(tuple.block.Height), []byte("block-bogus"))
  257. require.NoError(t, err)
  258. }
  259. bBlock := bs.LoadBlock(tuple.block.Height)
  260. bBlockMeta := bs.LoadBlockMeta(tuple.block.Height)
  261. if tuple.eraseSeenCommitInDB {
  262. db.Delete(calcSeenCommitKey(tuple.block.Height))
  263. }
  264. if tuple.corruptSeenCommitInDB {
  265. err := db.Set(calcSeenCommitKey(tuple.block.Height), []byte("bogus-seen-commit"))
  266. require.NoError(t, err)
  267. }
  268. bSeenCommit := bs.LoadSeenCommit(tuple.block.Height)
  269. commitHeight := tuple.block.Height - 1
  270. if tuple.eraseCommitInDB {
  271. db.Delete(calcBlockCommitKey(commitHeight))
  272. }
  273. if tuple.corruptCommitInDB {
  274. err := db.Set(calcBlockCommitKey(commitHeight), []byte("foo-bogus"))
  275. require.NoError(t, err)
  276. }
  277. bCommit := bs.LoadBlockCommit(commitHeight)
  278. return &quad{block: bBlock, seenCommit: bSeenCommit, commit: bCommit,
  279. meta: bBlockMeta}, nil
  280. })
  281. if subStr := tuple.wantPanic; subStr != "" {
  282. if panicErr == nil {
  283. t.Errorf("#%d: want a non-nil panic", i)
  284. } else if got := fmt.Sprintf("%#v", panicErr); !strings.Contains(got, subStr) {
  285. t.Errorf("#%d:\n\tgotErr: %q\nwant substring: %q", i, got, subStr)
  286. }
  287. continue
  288. }
  289. if tuple.wantErr {
  290. if err == nil {
  291. t.Errorf("#%d: got nil error", i)
  292. }
  293. continue
  294. }
  295. assert.Nil(t, panicErr, "#%d: unexpected panic", i)
  296. assert.Nil(t, err, "#%d: expecting a non-nil error", i)
  297. qua, ok := res.(*quad)
  298. if !ok || qua == nil {
  299. t.Errorf("#%d: got nil quad back; gotType=%T", i, res)
  300. continue
  301. }
  302. if tuple.eraseSeenCommitInDB {
  303. assert.Nil(t, qua.seenCommit,
  304. "erased the seenCommit in the DB hence we should get back a nil seenCommit")
  305. }
  306. if tuple.eraseCommitInDB {
  307. assert.Nil(t, qua.commit,
  308. "erased the commit in the DB hence we should get back a nil commit")
  309. }
  310. }
  311. }
  312. func TestLoadBlockPart(t *testing.T) {
  313. bs, db := freshBlockStore()
  314. height, index := int64(10), 1
  315. loadPart := func() (interface{}, error) {
  316. part := bs.LoadBlockPart(height, index)
  317. return part, nil
  318. }
  319. // Initially no contents.
  320. // 1. Requesting for a non-existent block shouldn't fail
  321. res, _, panicErr := doFn(loadPart)
  322. require.Nil(t, panicErr, "a non-existent block part shouldn't cause a panic")
  323. require.Nil(t, res, "a non-existent block part should return nil")
  324. // 2. Next save a corrupted block then try to load it
  325. err := db.Set(calcBlockPartKey(height, index), []byte("Tendermint"))
  326. require.NoError(t, err)
  327. res, _, panicErr = doFn(loadPart)
  328. require.NotNil(t, panicErr, "expecting a non-nil panic")
  329. require.Contains(t, panicErr.Error(), "unmarshal to tmproto.Part failed")
  330. // 3. A good block serialized and saved to the DB should be retrievable
  331. pb1, err := part1.ToProto()
  332. require.NoError(t, err)
  333. err = db.Set(calcBlockPartKey(height, index), mustEncode(pb1))
  334. require.NoError(t, err)
  335. gotPart, _, panicErr := doFn(loadPart)
  336. require.Nil(t, panicErr, "an existent and proper block should not panic")
  337. require.Nil(t, res, "a properly saved block should return a proper block")
  338. require.Equal(t, gotPart.(*types.Part), part1,
  339. "expecting successful retrieval of previously saved block")
  340. }
  341. func TestPruneBlocks(t *testing.T) {
  342. config := cfg.ResetTestRoot("blockchain_reactor_test")
  343. defer os.RemoveAll(config.RootDir)
  344. state, err := sm.LoadStateFromDBOrGenesisFile(dbm.NewMemDB(), config.GenesisFile())
  345. require.NoError(t, err)
  346. db := dbm.NewMemDB()
  347. bs := NewBlockStore(db)
  348. assert.EqualValues(t, 0, bs.Base())
  349. assert.EqualValues(t, 0, bs.Height())
  350. assert.EqualValues(t, 0, bs.Size())
  351. // pruning an empty store should error, even when pruning to 0
  352. _, err = bs.PruneBlocks(1)
  353. require.Error(t, err)
  354. _, err = bs.PruneBlocks(0)
  355. require.Error(t, err)
  356. // make more than 1000 blocks, to test batch deletions
  357. for h := int64(1); h <= 1500; h++ {
  358. block := makeBlock(h, state, new(types.Commit))
  359. partSet := block.MakePartSet(2)
  360. seenCommit := makeTestCommit(h, tmtime.Now())
  361. bs.SaveBlock(block, partSet, seenCommit)
  362. }
  363. assert.EqualValues(t, 1, bs.Base())
  364. assert.EqualValues(t, 1500, bs.Height())
  365. assert.EqualValues(t, 1500, bs.Size())
  366. prunedBlock := bs.LoadBlock(1199)
  367. // Check that basic pruning works
  368. pruned, err := bs.PruneBlocks(1200)
  369. require.NoError(t, err)
  370. assert.EqualValues(t, 1199, pruned)
  371. assert.EqualValues(t, 1200, bs.Base())
  372. assert.EqualValues(t, 1500, bs.Height())
  373. assert.EqualValues(t, 301, bs.Size())
  374. assert.EqualValues(t, tmstore.BlockStoreState{
  375. Base: 1200,
  376. Height: 1500,
  377. }, LoadBlockStoreState(db))
  378. require.NotNil(t, bs.LoadBlock(1200))
  379. require.Nil(t, bs.LoadBlock(1199))
  380. require.Nil(t, bs.LoadBlockByHash(prunedBlock.Hash()))
  381. require.Nil(t, bs.LoadBlockCommit(1199))
  382. require.Nil(t, bs.LoadBlockMeta(1199))
  383. require.Nil(t, bs.LoadBlockPart(1199, 1))
  384. for i := int64(1); i < 1200; i++ {
  385. require.Nil(t, bs.LoadBlock(i))
  386. }
  387. for i := int64(1200); i <= 1500; i++ {
  388. require.NotNil(t, bs.LoadBlock(i))
  389. }
  390. // Pruning below the current base should error
  391. _, err = bs.PruneBlocks(1199)
  392. require.Error(t, err)
  393. // Pruning to the current base should work
  394. pruned, err = bs.PruneBlocks(1200)
  395. require.NoError(t, err)
  396. assert.EqualValues(t, 0, pruned)
  397. // Pruning again should work
  398. pruned, err = bs.PruneBlocks(1300)
  399. require.NoError(t, err)
  400. assert.EqualValues(t, 100, pruned)
  401. assert.EqualValues(t, 1300, bs.Base())
  402. // Pruning beyond the current height should error
  403. _, err = bs.PruneBlocks(1501)
  404. require.Error(t, err)
  405. // Pruning to the current height should work
  406. pruned, err = bs.PruneBlocks(1500)
  407. require.NoError(t, err)
  408. assert.EqualValues(t, 200, pruned)
  409. assert.Nil(t, bs.LoadBlock(1499))
  410. assert.NotNil(t, bs.LoadBlock(1500))
  411. assert.Nil(t, bs.LoadBlock(1501))
  412. }
  413. func TestLoadBlockMeta(t *testing.T) {
  414. bs, db := freshBlockStore()
  415. height := int64(10)
  416. loadMeta := func() (interface{}, error) {
  417. meta := bs.LoadBlockMeta(height)
  418. return meta, nil
  419. }
  420. // Initially no contents.
  421. // 1. Requesting for a non-existent blockMeta shouldn't fail
  422. res, _, panicErr := doFn(loadMeta)
  423. require.Nil(t, panicErr, "a non-existent blockMeta shouldn't cause a panic")
  424. require.Nil(t, res, "a non-existent blockMeta should return nil")
  425. // 2. Next save a corrupted blockMeta then try to load it
  426. err := db.Set(calcBlockMetaKey(height), []byte("Tendermint-Meta"))
  427. require.NoError(t, err)
  428. res, _, panicErr = doFn(loadMeta)
  429. require.NotNil(t, panicErr, "expecting a non-nil panic")
  430. require.Contains(t, panicErr.Error(), "unmarshal to tmproto.BlockMeta")
  431. // 3. A good blockMeta serialized and saved to the DB should be retrievable
  432. meta := &types.BlockMeta{Header: types.Header{Height: 1, ProposerAddress: tmrand.Bytes(crypto.AddressSize)}}
  433. pbm := meta.ToProto()
  434. err = db.Set(calcBlockMetaKey(height), mustEncode(pbm))
  435. require.NoError(t, err)
  436. gotMeta, _, panicErr := doFn(loadMeta)
  437. require.Nil(t, panicErr, "an existent and proper block should not panic")
  438. require.Nil(t, res, "a properly saved blockMeta should return a proper blocMeta ")
  439. pbmeta := meta.ToProto()
  440. if gmeta, ok := gotMeta.(*types.BlockMeta); ok {
  441. pbgotMeta := gmeta.ToProto()
  442. require.Equal(t, mustEncode(pbmeta), mustEncode(pbgotMeta),
  443. "expecting successful retrieval of previously saved blockMeta")
  444. }
  445. }
  446. func TestBlockFetchAtHeight(t *testing.T) {
  447. state, bs, cleanup := makeStateAndBlockStore(log.NewTMLogger(new(bytes.Buffer)))
  448. defer cleanup()
  449. require.Equal(t, bs.Height(), int64(0), "initially the height should be zero")
  450. block := makeBlock(bs.Height()+1, state, new(types.Commit))
  451. partSet := block.MakePartSet(2)
  452. seenCommit := makeTestCommit(10, tmtime.Now())
  453. bs.SaveBlock(block, partSet, seenCommit)
  454. require.Equal(t, bs.Height(), block.Header.Height, "expecting the new height to be changed")
  455. blockAtHeight := bs.LoadBlock(bs.Height())
  456. b1, err := block.ToProto()
  457. require.NoError(t, err)
  458. b2, err := blockAtHeight.ToProto()
  459. require.NoError(t, err)
  460. bz1 := mustEncode(b1)
  461. bz2 := mustEncode(b2)
  462. require.Equal(t, bz1, bz2)
  463. require.Equal(t, block.Hash(), blockAtHeight.Hash(),
  464. "expecting a successful load of the last saved block")
  465. blockAtHeightPlus1 := bs.LoadBlock(bs.Height() + 1)
  466. require.Nil(t, blockAtHeightPlus1, "expecting an unsuccessful load of Height()+1")
  467. blockAtHeightPlus2 := bs.LoadBlock(bs.Height() + 2)
  468. require.Nil(t, blockAtHeightPlus2, "expecting an unsuccessful load of Height()+2")
  469. }
  470. func doFn(fn func() (interface{}, error)) (res interface{}, err error, panicErr error) {
  471. defer func() {
  472. if r := recover(); r != nil {
  473. switch e := r.(type) {
  474. case error:
  475. panicErr = e
  476. case string:
  477. panicErr = fmt.Errorf("%s", e)
  478. default:
  479. if st, ok := r.(fmt.Stringer); ok {
  480. panicErr = fmt.Errorf("%s", st)
  481. } else {
  482. panicErr = fmt.Errorf("%s", debug.Stack())
  483. }
  484. }
  485. }
  486. }()
  487. res, err = fn()
  488. return res, err, panicErr
  489. }
  490. func newBlock(hdr types.Header, lastCommit *types.Commit) *types.Block {
  491. return &types.Block{
  492. Header: hdr,
  493. LastCommit: lastCommit,
  494. }
  495. }