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.

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