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.

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