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.

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