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.

589 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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. "fmt"
  4. stdlog "log"
  5. "os"
  6. "runtime/debug"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/require"
  12. dbm "github.com/tendermint/tm-db"
  13. "github.com/tendermint/tendermint/config"
  14. "github.com/tendermint/tendermint/crypto"
  15. sm "github.com/tendermint/tendermint/internal/state"
  16. "github.com/tendermint/tendermint/internal/state/test/factory"
  17. "github.com/tendermint/tendermint/libs/log"
  18. tmrand "github.com/tendermint/tendermint/libs/rand"
  19. tmtime "github.com/tendermint/tendermint/libs/time"
  20. "github.com/tendermint/tendermint/types"
  21. "github.com/tendermint/tendermint/version"
  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(
  35. height,
  36. 0,
  37. types.BlockID{
  38. Hash: crypto.CRandBytes(32),
  39. PartSetHeader: types.PartSetHeader{Hash: crypto.CRandBytes(32), Total: 2},
  40. },
  41. commitSigs)
  42. }
  43. func makeStateAndBlockStore(logger log.Logger) (sm.State, *BlockStore, cleanupFunc, error) {
  44. cfg, err := config.ResetTestRoot("blockchain_reactor_test")
  45. if err != nil {
  46. return sm.State{}, nil, nil, err
  47. }
  48. blockDB := dbm.NewMemDB()
  49. state, err := sm.MakeGenesisStateFromFile(cfg.GenesisFile())
  50. if err != nil {
  51. return sm.State{}, nil, nil, fmt.Errorf("error constructing state from genesis file: %w", err)
  52. }
  53. return state, NewBlockStore(blockDB), func() { os.RemoveAll(cfg.RootDir) }, nil
  54. }
  55. func freshBlockStore() (*BlockStore, dbm.DB) {
  56. db := dbm.NewMemDB()
  57. return NewBlockStore(db), db
  58. }
  59. var (
  60. state sm.State
  61. block *types.Block
  62. partSet *types.PartSet
  63. part1 *types.Part
  64. part2 *types.Part
  65. seenCommit1 *types.Commit
  66. )
  67. func TestMain(m *testing.M) {
  68. var cleanup cleanupFunc
  69. var err error
  70. state, _, cleanup, err = makeStateAndBlockStore(log.NewNopLogger())
  71. if err != nil {
  72. stdlog.Fatal(err)
  73. }
  74. block, err = factory.MakeBlock(state, 1, new(types.Commit))
  75. if err != nil {
  76. stdlog.Fatal(err)
  77. }
  78. partSet, err = block.MakePartSet(2)
  79. if err != nil {
  80. stdlog.Fatal(err)
  81. }
  82. part1 = partSet.GetPart(0)
  83. part2 = partSet.GetPart(1)
  84. seenCommit1 = makeTestCommit(10, tmtime.Now())
  85. code := m.Run()
  86. cleanup()
  87. os.Exit(code)
  88. }
  89. // TODO: This test should be simplified ...
  90. func TestBlockStoreSaveLoadBlock(t *testing.T) {
  91. state, bs, cleanup, err := makeStateAndBlockStore(log.NewNopLogger())
  92. defer cleanup()
  93. require.NoError(t, err)
  94. require.Equal(t, bs.Base(), int64(0), "initially the base should be zero")
  95. require.Equal(t, bs.Height(), int64(0), "initially the height should be zero")
  96. // check there are no blocks at various heights
  97. noBlockHeights := []int64{0, -1, 100, 1000, 2}
  98. for i, height := range noBlockHeights {
  99. if g := bs.LoadBlock(height); g != nil {
  100. t.Errorf("#%d: height(%d) got a block; want nil", i, height)
  101. }
  102. }
  103. // save a block
  104. block, err := factory.MakeBlock(state, bs.Height()+1, new(types.Commit))
  105. require.NoError(t, err)
  106. validPartSet, err := block.MakePartSet(2)
  107. require.NoError(t, err)
  108. seenCommit := makeTestCommit(10, tmtime.Now())
  109. bs.SaveBlock(block, partSet, seenCommit)
  110. require.EqualValues(t, 1, bs.Base(), "expecting the new height to be changed")
  111. require.EqualValues(t, block.Header.Height, bs.Height(), "expecting the new height to be changed")
  112. incompletePartSet := types.NewPartSetFromHeader(types.PartSetHeader{Total: 2})
  113. uncontiguousPartSet := types.NewPartSetFromHeader(types.PartSetHeader{Total: 0})
  114. _, err = uncontiguousPartSet.AddPart(part2)
  115. require.Error(t, err)
  116. header1 := types.Header{
  117. Version: version.Consensus{Block: version.BlockProtocol},
  118. Height: 1,
  119. ChainID: "block_test",
  120. Time: tmtime.Now(),
  121. ProposerAddress: tmrand.Bytes(crypto.AddressSize),
  122. }
  123. // End of setup, test data
  124. commitAtH10 := makeTestCommit(10, tmtime.Now())
  125. tuples := []struct {
  126. block *types.Block
  127. parts *types.PartSet
  128. seenCommit *types.Commit
  129. wantPanic string
  130. wantErr bool
  131. corruptBlockInDB bool
  132. corruptCommitInDB bool
  133. corruptSeenCommitInDB bool
  134. eraseCommitInDB bool
  135. eraseSeenCommitInDB bool
  136. }{
  137. {
  138. block: newBlock(header1, commitAtH10),
  139. parts: validPartSet,
  140. seenCommit: seenCommit1,
  141. },
  142. {
  143. block: nil,
  144. wantPanic: "only save a non-nil block",
  145. },
  146. {
  147. block: newBlock( // New block at height 5 in empty block store is fine
  148. types.Header{
  149. Version: version.Consensus{Block: version.BlockProtocol},
  150. Height: 5,
  151. ChainID: "block_test",
  152. Time: tmtime.Now(),
  153. ProposerAddress: tmrand.Bytes(crypto.AddressSize)},
  154. makeTestCommit(5, tmtime.Now()),
  155. ),
  156. parts: validPartSet,
  157. seenCommit: makeTestCommit(5, tmtime.Now()),
  158. },
  159. {
  160. block: newBlock(header1, commitAtH10),
  161. parts: incompletePartSet,
  162. wantPanic: "only save complete block", // incomplete parts
  163. },
  164. {
  165. block: newBlock(header1, commitAtH10),
  166. parts: validPartSet,
  167. seenCommit: seenCommit1,
  168. corruptCommitInDB: true, // Corrupt the DB's commit entry
  169. wantPanic: "error reading block commit",
  170. },
  171. {
  172. block: newBlock(header1, commitAtH10),
  173. parts: validPartSet,
  174. seenCommit: seenCommit1,
  175. wantPanic: "unmarshal to tmproto.BlockMeta",
  176. corruptBlockInDB: true, // Corrupt the DB's block entry
  177. },
  178. {
  179. block: newBlock(header1, commitAtH10),
  180. parts: validPartSet,
  181. seenCommit: seenCommit1,
  182. // Expecting no error and we want a nil back
  183. eraseSeenCommitInDB: true,
  184. },
  185. {
  186. block: newBlock(header1, commitAtH10),
  187. parts: validPartSet,
  188. seenCommit: seenCommit1,
  189. corruptSeenCommitInDB: true,
  190. wantPanic: "error reading block seen commit",
  191. },
  192. {
  193. block: newBlock(header1, commitAtH10),
  194. parts: validPartSet,
  195. seenCommit: seenCommit1,
  196. // Expecting no error and we want a nil back
  197. eraseCommitInDB: true,
  198. },
  199. }
  200. type quad struct {
  201. block *types.Block
  202. commit *types.Commit
  203. meta *types.BlockMeta
  204. seenCommit *types.Commit
  205. }
  206. for i, tuple := range tuples {
  207. tuple := tuple
  208. bs, db := freshBlockStore()
  209. // SaveBlock
  210. res, err, panicErr := doFn(func() (interface{}, error) {
  211. bs.SaveBlock(tuple.block, tuple.parts, tuple.seenCommit)
  212. if tuple.block == nil {
  213. return nil, nil
  214. }
  215. if tuple.corruptBlockInDB {
  216. err := db.Set(blockMetaKey(tuple.block.Height), []byte("block-bogus"))
  217. require.NoError(t, err)
  218. }
  219. bBlock := bs.LoadBlock(tuple.block.Height)
  220. bBlockMeta := bs.LoadBlockMeta(tuple.block.Height)
  221. if tuple.eraseSeenCommitInDB {
  222. err := db.Delete(seenCommitKey())
  223. require.NoError(t, err)
  224. }
  225. if tuple.corruptSeenCommitInDB {
  226. err := db.Set(seenCommitKey(), []byte("bogus-seen-commit"))
  227. require.NoError(t, err)
  228. }
  229. bSeenCommit := bs.LoadSeenCommit()
  230. commitHeight := tuple.block.Height - 1
  231. if tuple.eraseCommitInDB {
  232. err := db.Delete(blockCommitKey(commitHeight))
  233. require.NoError(t, err)
  234. }
  235. if tuple.corruptCommitInDB {
  236. err := db.Set(blockCommitKey(commitHeight), []byte("foo-bogus"))
  237. require.NoError(t, err)
  238. }
  239. bCommit := bs.LoadBlockCommit(commitHeight)
  240. return &quad{block: bBlock, seenCommit: bSeenCommit, commit: bCommit,
  241. meta: bBlockMeta}, nil
  242. })
  243. if subStr := tuple.wantPanic; subStr != "" {
  244. if panicErr == nil {
  245. t.Errorf("#%d: want a non-nil panic", i)
  246. } else if got := fmt.Sprintf("%#v", panicErr); !strings.Contains(got, subStr) {
  247. t.Errorf("#%d:\n\tgotErr: %q\nwant substring: %q", i, got, subStr)
  248. }
  249. continue
  250. }
  251. if tuple.wantErr {
  252. if err == nil {
  253. t.Errorf("#%d: got nil error", i)
  254. }
  255. continue
  256. }
  257. assert.Nil(t, panicErr, "#%d: unexpected panic", i)
  258. assert.NoError(t, err, "#%d: expecting a non-nil error", i)
  259. qua, ok := res.(*quad)
  260. if !ok || qua == nil {
  261. t.Errorf("#%d: got nil quad back; gotType=%T", i, res)
  262. continue
  263. }
  264. if tuple.eraseSeenCommitInDB {
  265. assert.Nil(t, qua.seenCommit,
  266. "erased the seenCommit in the DB hence we should get back a nil seenCommit")
  267. }
  268. if tuple.eraseCommitInDB {
  269. assert.Nil(t, qua.commit,
  270. "erased the commit in the DB hence we should get back a nil commit")
  271. }
  272. }
  273. }
  274. func TestLoadBaseMeta(t *testing.T) {
  275. cfg, err := config.ResetTestRoot("blockchain_reactor_test")
  276. require.NoError(t, err)
  277. defer os.RemoveAll(cfg.RootDir)
  278. state, err := sm.MakeGenesisStateFromFile(cfg.GenesisFile())
  279. require.NoError(t, err)
  280. bs := NewBlockStore(dbm.NewMemDB())
  281. for h := int64(1); h <= 10; h++ {
  282. block, err := factory.MakeBlock(state, h, new(types.Commit))
  283. require.NoError(t, err)
  284. partSet, err := block.MakePartSet(2)
  285. require.NoError(t, err)
  286. seenCommit := makeTestCommit(h, tmtime.Now())
  287. bs.SaveBlock(block, partSet, seenCommit)
  288. }
  289. pruned, err := bs.PruneBlocks(4)
  290. require.NoError(t, err)
  291. assert.EqualValues(t, 3, pruned)
  292. baseBlock := bs.LoadBaseMeta()
  293. assert.EqualValues(t, 4, baseBlock.Header.Height)
  294. assert.EqualValues(t, 4, bs.Base())
  295. }
  296. func TestLoadBlockPart(t *testing.T) {
  297. bs, db := freshBlockStore()
  298. height, index := int64(10), 1
  299. loadPart := func() (interface{}, error) {
  300. part := bs.LoadBlockPart(height, index)
  301. return part, nil
  302. }
  303. // Initially no contents.
  304. // 1. Requesting for a non-existent block shouldn't fail
  305. res, _, panicErr := doFn(loadPart)
  306. require.Nil(t, panicErr, "a non-existent block part shouldn't cause a panic")
  307. require.Nil(t, res, "a non-existent block part should return nil")
  308. // 2. Next save a corrupted block then try to load it
  309. err := db.Set(blockPartKey(height, index), []byte("Tendermint"))
  310. require.NoError(t, err)
  311. res, _, panicErr = doFn(loadPart)
  312. require.NotNil(t, panicErr, "expecting a non-nil panic")
  313. require.Contains(t, panicErr.Error(), "unmarshal to tmproto.Part failed")
  314. // 3. A good block serialized and saved to the DB should be retrievable
  315. pb1, err := part1.ToProto()
  316. require.NoError(t, err)
  317. err = db.Set(blockPartKey(height, index), mustEncode(pb1))
  318. require.NoError(t, err)
  319. gotPart, _, panicErr := doFn(loadPart)
  320. require.Nil(t, panicErr, "an existent and proper block should not panic")
  321. require.Nil(t, res, "a properly saved block should return a proper block")
  322. require.Equal(t, gotPart.(*types.Part), part1,
  323. "expecting successful retrieval of previously saved block")
  324. }
  325. func TestPruneBlocks(t *testing.T) {
  326. cfg, err := config.ResetTestRoot("blockchain_reactor_test")
  327. require.NoError(t, err)
  328. defer os.RemoveAll(cfg.RootDir)
  329. state, err := sm.MakeGenesisStateFromFile(cfg.GenesisFile())
  330. require.NoError(t, err)
  331. db := dbm.NewMemDB()
  332. bs := NewBlockStore(db)
  333. assert.EqualValues(t, 0, bs.Base())
  334. assert.EqualValues(t, 0, bs.Height())
  335. assert.EqualValues(t, 0, bs.Size())
  336. _, err = bs.PruneBlocks(0)
  337. require.Error(t, err)
  338. // make more than 1000 blocks, to test batch deletions
  339. for h := int64(1); h <= 1500; h++ {
  340. block, err := factory.MakeBlock(state, h, new(types.Commit))
  341. require.NoError(t, err)
  342. partSet, err := block.MakePartSet(2)
  343. require.NoError(t, err)
  344. seenCommit := makeTestCommit(h, tmtime.Now())
  345. bs.SaveBlock(block, partSet, seenCommit)
  346. }
  347. assert.EqualValues(t, 1, bs.Base())
  348. assert.EqualValues(t, 1500, bs.Height())
  349. assert.EqualValues(t, 1500, bs.Size())
  350. prunedBlock := bs.LoadBlock(1199)
  351. // Check that basic pruning works
  352. pruned, err := bs.PruneBlocks(1200)
  353. require.NoError(t, err)
  354. assert.EqualValues(t, 1199, pruned)
  355. assert.EqualValues(t, 1200, bs.Base())
  356. assert.EqualValues(t, 1500, bs.Height())
  357. assert.EqualValues(t, 301, bs.Size())
  358. require.NotNil(t, bs.LoadBlock(1200))
  359. require.Nil(t, bs.LoadBlock(1199))
  360. require.Nil(t, bs.LoadBlockByHash(prunedBlock.Hash()))
  361. require.Nil(t, bs.LoadBlockCommit(1199))
  362. require.Nil(t, bs.LoadBlockMeta(1199))
  363. require.Nil(t, bs.LoadBlockPart(1199, 1))
  364. for i := int64(1); i < 1200; i++ {
  365. require.Nil(t, bs.LoadBlock(i))
  366. }
  367. for i := int64(1200); i <= 1500; i++ {
  368. require.NotNil(t, bs.LoadBlock(i))
  369. }
  370. // Pruning below the current base should not error
  371. _, err = bs.PruneBlocks(1199)
  372. require.NoError(t, err)
  373. // Pruning to the current base should work
  374. pruned, err = bs.PruneBlocks(1200)
  375. require.NoError(t, err)
  376. assert.EqualValues(t, 0, pruned)
  377. // Pruning again should work
  378. pruned, err = bs.PruneBlocks(1300)
  379. require.NoError(t, err)
  380. assert.EqualValues(t, 100, pruned)
  381. assert.EqualValues(t, 1300, bs.Base())
  382. // Pruning beyond the current height should error
  383. _, err = bs.PruneBlocks(1501)
  384. require.Error(t, err)
  385. // Pruning to the current height should work
  386. pruned, err = bs.PruneBlocks(1500)
  387. require.NoError(t, err)
  388. assert.EqualValues(t, 200, pruned)
  389. assert.Nil(t, bs.LoadBlock(1499))
  390. assert.NotNil(t, bs.LoadBlock(1500))
  391. assert.Nil(t, bs.LoadBlock(1501))
  392. }
  393. func TestLoadBlockMeta(t *testing.T) {
  394. bs, db := freshBlockStore()
  395. height := int64(10)
  396. loadMeta := func() (interface{}, error) {
  397. meta := bs.LoadBlockMeta(height)
  398. return meta, nil
  399. }
  400. // Initially no contents.
  401. // 1. Requesting for a non-existent blockMeta shouldn't fail
  402. res, _, panicErr := doFn(loadMeta)
  403. require.Nil(t, panicErr, "a non-existent blockMeta shouldn't cause a panic")
  404. require.Nil(t, res, "a non-existent blockMeta should return nil")
  405. // 2. Next save a corrupted blockMeta then try to load it
  406. err := db.Set(blockMetaKey(height), []byte("Tendermint-Meta"))
  407. require.NoError(t, err)
  408. res, _, panicErr = doFn(loadMeta)
  409. require.NotNil(t, panicErr, "expecting a non-nil panic")
  410. require.Contains(t, panicErr.Error(), "unmarshal to tmproto.BlockMeta")
  411. // 3. A good blockMeta serialized and saved to the DB should be retrievable
  412. meta := &types.BlockMeta{Header: types.Header{
  413. Version: version.Consensus{
  414. Block: version.BlockProtocol, App: 0}, Height: 1, ProposerAddress: tmrand.Bytes(crypto.AddressSize)}}
  415. pbm := meta.ToProto()
  416. err = db.Set(blockMetaKey(height), mustEncode(pbm))
  417. require.NoError(t, err)
  418. gotMeta, _, panicErr := doFn(loadMeta)
  419. require.Nil(t, panicErr, "an existent and proper block should not panic")
  420. require.Nil(t, res, "a properly saved blockMeta should return a proper blocMeta ")
  421. pbmeta := meta.ToProto()
  422. if gmeta, ok := gotMeta.(*types.BlockMeta); ok {
  423. pbgotMeta := gmeta.ToProto()
  424. require.Equal(t, mustEncode(pbmeta), mustEncode(pbgotMeta),
  425. "expecting successful retrieval of previously saved blockMeta")
  426. }
  427. }
  428. func TestBlockFetchAtHeight(t *testing.T) {
  429. state, bs, cleanup, err := makeStateAndBlockStore(log.NewNopLogger())
  430. defer cleanup()
  431. require.NoError(t, err)
  432. require.Equal(t, bs.Height(), int64(0), "initially the height should be zero")
  433. block, err := factory.MakeBlock(state, bs.Height()+1, new(types.Commit))
  434. require.NoError(t, err)
  435. partSet, err := block.MakePartSet(2)
  436. require.NoError(t, err)
  437. seenCommit := makeTestCommit(10, tmtime.Now())
  438. bs.SaveBlock(block, partSet, seenCommit)
  439. require.Equal(t, bs.Height(), block.Header.Height, "expecting the new height to be changed")
  440. blockAtHeight := bs.LoadBlock(bs.Height())
  441. b1, err := block.ToProto()
  442. require.NoError(t, err)
  443. b2, err := blockAtHeight.ToProto()
  444. require.NoError(t, err)
  445. bz1 := mustEncode(b1)
  446. bz2 := mustEncode(b2)
  447. require.Equal(t, bz1, bz2)
  448. require.Equal(t, block.Hash(), blockAtHeight.Hash(),
  449. "expecting a successful load of the last saved block")
  450. blockAtHeightPlus1 := bs.LoadBlock(bs.Height() + 1)
  451. require.Nil(t, blockAtHeightPlus1, "expecting an unsuccessful load of Height()+1")
  452. blockAtHeightPlus2 := bs.LoadBlock(bs.Height() + 2)
  453. require.Nil(t, blockAtHeightPlus2, "expecting an unsuccessful load of Height()+2")
  454. }
  455. func TestSeenAndCanonicalCommit(t *testing.T) {
  456. bs, _ := freshBlockStore()
  457. loadCommit := func() (interface{}, error) {
  458. meta := bs.LoadSeenCommit()
  459. return meta, nil
  460. }
  461. // Initially no contents.
  462. // 1. Requesting for a non-existent blockMeta shouldn't fail
  463. res, _, panicErr := doFn(loadCommit)
  464. require.Nil(t, panicErr, "a non-existent blockMeta shouldn't cause a panic")
  465. require.Nil(t, res, "a non-existent blockMeta should return nil")
  466. // produce a few blocks and check that the correct seen and cannoncial commits
  467. // are persisted.
  468. for h := int64(3); h <= 5; h++ {
  469. blockCommit := makeTestCommit(h-1, tmtime.Now())
  470. block, err := factory.MakeBlock(state, h, blockCommit)
  471. require.NoError(t, err)
  472. partSet, err := block.MakePartSet(2)
  473. require.NoError(t, err)
  474. seenCommit := makeTestCommit(h, tmtime.Now())
  475. bs.SaveBlock(block, partSet, seenCommit)
  476. c3 := bs.LoadSeenCommit()
  477. require.NotNil(t, c3)
  478. require.Equal(t, h, c3.Height)
  479. require.Equal(t, seenCommit.Hash(), c3.Hash())
  480. c5 := bs.LoadBlockCommit(h)
  481. require.Nil(t, c5)
  482. c6 := bs.LoadBlockCommit(h - 1)
  483. require.Equal(t, blockCommit.Hash(), c6.Hash())
  484. }
  485. }
  486. func doFn(fn func() (interface{}, error)) (res interface{}, err error, panicErr error) {
  487. defer func() {
  488. if r := recover(); r != nil {
  489. switch e := r.(type) {
  490. case error:
  491. panicErr = e
  492. case string:
  493. panicErr = fmt.Errorf("%s", e)
  494. default:
  495. if st, ok := r.(fmt.Stringer); ok {
  496. panicErr = fmt.Errorf("%s", st)
  497. } else {
  498. panicErr = fmt.Errorf("%s", debug.Stack())
  499. }
  500. }
  501. }
  502. }()
  503. res, err = fn()
  504. return res, err, panicErr
  505. }
  506. func newBlock(hdr types.Header, lastCommit *types.Commit) *types.Block {
  507. return &types.Block{
  508. Header: hdr,
  509. LastCommit: lastCommit,
  510. }
  511. }