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.

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