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.

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