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.

436 lines
13 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
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
  1. package store
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os"
  6. "runtime/debug"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/pkg/errors"
  11. "github.com/stretchr/testify/assert"
  12. "github.com/stretchr/testify/require"
  13. db "github.com/tendermint/tm-db"
  14. dbm "github.com/tendermint/tm-db"
  15. cfg "github.com/tendermint/tendermint/config"
  16. "github.com/tendermint/tendermint/libs/log"
  17. sm "github.com/tendermint/tendermint/state"
  18. "github.com/tendermint/tendermint/types"
  19. tmtime "github.com/tendermint/tendermint/types/time"
  20. )
  21. // A cleanupFunc cleans up any config / test files created for a particular
  22. // test.
  23. type cleanupFunc func()
  24. // make a Commit with a single vote containing just the height and a timestamp
  25. func makeTestCommit(height int64, timestamp time.Time) *types.Commit {
  26. commitSigs := []*types.CommitSig{{Height: height, Timestamp: timestamp}}
  27. return types.NewCommit(types.BlockID{}, commitSigs)
  28. }
  29. func makeTxs(height int64) (txs []types.Tx) {
  30. for i := 0; i < 10; i++ {
  31. txs = append(txs, types.Tx([]byte{byte(height), byte(i)}))
  32. }
  33. return txs
  34. }
  35. func makeBlock(height int64, state sm.State, lastCommit *types.Commit) *types.Block {
  36. block, _ := state.MakeBlock(height, makeTxs(height), lastCommit, nil, state.Validators.GetProposer().Address)
  37. return block
  38. }
  39. func makeStateAndBlockStore(logger log.Logger) (sm.State, *BlockStore, cleanupFunc) {
  40. config := cfg.ResetTestRoot("blockchain_reactor_test")
  41. // blockDB := dbm.NewDebugDB("blockDB", dbm.NewMemDB())
  42. // stateDB := dbm.NewDebugDB("stateDB", dbm.NewMemDB())
  43. blockDB := dbm.NewMemDB()
  44. stateDB := dbm.NewMemDB()
  45. state, err := sm.LoadStateFromDBOrGenesisFile(stateDB, config.GenesisFile())
  46. if err != nil {
  47. panic(errors.Wrap(err, "error constructing state from genesis file"))
  48. }
  49. return state, NewBlockStore(blockDB), func() { os.RemoveAll(config.RootDir) }
  50. }
  51. func TestLoadBlockStoreStateJSON(t *testing.T) {
  52. db := db.NewMemDB()
  53. bsj := &BlockStoreStateJSON{Height: 1000}
  54. bsj.Save(db)
  55. retrBSJ := LoadBlockStoreStateJSON(db)
  56. assert.Equal(t, *bsj, retrBSJ, "expected the retrieved DBs to match")
  57. }
  58. func TestNewBlockStore(t *testing.T) {
  59. db := db.NewMemDB()
  60. db.Set(blockStoreKey, []byte(`{"height": "10000"}`))
  61. bs := NewBlockStore(db)
  62. require.Equal(t, int64(10000), bs.Height(), "failed to properly parse blockstore")
  63. panicCausers := []struct {
  64. data []byte
  65. wantErr string
  66. }{
  67. {[]byte("artful-doger"), "not unmarshal bytes"},
  68. {[]byte(" "), "unmarshal bytes"},
  69. }
  70. for i, tt := range panicCausers {
  71. tt := tt
  72. // Expecting a panic here on trying to parse an invalid blockStore
  73. _, _, panicErr := doFn(func() (interface{}, error) {
  74. db.Set(blockStoreKey, tt.data)
  75. _ = NewBlockStore(db)
  76. return nil, nil
  77. })
  78. require.NotNil(t, panicErr, "#%d panicCauser: %q expected a panic", i, tt.data)
  79. assert.Contains(t, fmt.Sprintf("%#v", panicErr), tt.wantErr, "#%d data: %q", i, tt.data)
  80. }
  81. db.Set(blockStoreKey, nil)
  82. bs = NewBlockStore(db)
  83. assert.Equal(t, bs.Height(), int64(0), "expecting nil bytes to be unmarshaled alright")
  84. }
  85. func freshBlockStore() (*BlockStore, db.DB) {
  86. db := db.NewMemDB()
  87. return NewBlockStore(db), db
  88. }
  89. var (
  90. state sm.State
  91. block *types.Block
  92. partSet *types.PartSet
  93. part1 *types.Part
  94. part2 *types.Part
  95. seenCommit1 *types.Commit
  96. )
  97. func TestMain(m *testing.M) {
  98. var cleanup cleanupFunc
  99. state, _, cleanup = makeStateAndBlockStore(log.NewTMLogger(new(bytes.Buffer)))
  100. block = makeBlock(1, state, new(types.Commit))
  101. partSet = block.MakePartSet(2)
  102. part1 = partSet.GetPart(0)
  103. part2 = partSet.GetPart(1)
  104. seenCommit1 = makeTestCommit(10, tmtime.Now())
  105. code := m.Run()
  106. cleanup()
  107. os.Exit(code)
  108. }
  109. // TODO: This test should be simplified ...
  110. func TestBlockStoreSaveLoadBlock(t *testing.T) {
  111. state, bs, cleanup := makeStateAndBlockStore(log.NewTMLogger(new(bytes.Buffer)))
  112. defer cleanup()
  113. require.Equal(t, bs.Height(), int64(0), "initially the height should be zero")
  114. // check there are no blocks at various heights
  115. noBlockHeights := []int64{0, -1, 100, 1000, 2}
  116. for i, height := range noBlockHeights {
  117. if g := bs.LoadBlock(height); g != nil {
  118. t.Errorf("#%d: height(%d) got a block; want nil", i, height)
  119. }
  120. }
  121. // save a block
  122. block := makeBlock(bs.Height()+1, state, new(types.Commit))
  123. validPartSet := block.MakePartSet(2)
  124. seenCommit := makeTestCommit(10, tmtime.Now())
  125. bs.SaveBlock(block, partSet, seenCommit)
  126. require.Equal(t, bs.Height(), block.Header.Height, "expecting the new height to be changed")
  127. incompletePartSet := types.NewPartSetFromHeader(types.PartSetHeader{Total: 2})
  128. uncontiguousPartSet := types.NewPartSetFromHeader(types.PartSetHeader{Total: 0})
  129. uncontiguousPartSet.AddPart(part2)
  130. header1 := types.Header{
  131. Height: 1,
  132. NumTxs: 100,
  133. ChainID: "block_test",
  134. Time: tmtime.Now(),
  135. }
  136. header2 := header1
  137. header2.Height = 4
  138. // End of setup, test data
  139. commitAtH10 := makeTestCommit(10, tmtime.Now())
  140. tuples := []struct {
  141. block *types.Block
  142. parts *types.PartSet
  143. seenCommit *types.Commit
  144. wantPanic string
  145. wantErr bool
  146. corruptBlockInDB bool
  147. corruptCommitInDB bool
  148. corruptSeenCommitInDB bool
  149. eraseCommitInDB bool
  150. eraseSeenCommitInDB bool
  151. }{
  152. {
  153. block: newBlock(header1, commitAtH10),
  154. parts: validPartSet,
  155. seenCommit: seenCommit1,
  156. },
  157. {
  158. block: nil,
  159. wantPanic: "only save a non-nil block",
  160. },
  161. {
  162. block: newBlock(header2, commitAtH10),
  163. parts: uncontiguousPartSet,
  164. wantPanic: "only save contiguous blocks", // and incomplete and uncontiguous parts
  165. },
  166. {
  167. block: newBlock(header1, commitAtH10),
  168. parts: incompletePartSet,
  169. wantPanic: "only save complete block", // incomplete parts
  170. },
  171. {
  172. block: newBlock(header1, commitAtH10),
  173. parts: validPartSet,
  174. seenCommit: seenCommit1,
  175. corruptCommitInDB: true, // Corrupt the DB's commit entry
  176. wantPanic: "unmarshal to types.Commit failed",
  177. },
  178. {
  179. block: newBlock(header1, commitAtH10),
  180. parts: validPartSet,
  181. seenCommit: seenCommit1,
  182. wantPanic: "unmarshal to types.BlockMeta failed",
  183. corruptBlockInDB: true, // Corrupt the DB's block entry
  184. },
  185. {
  186. block: newBlock(header1, commitAtH10),
  187. parts: validPartSet,
  188. seenCommit: seenCommit1,
  189. // Expecting no error and we want a nil back
  190. eraseSeenCommitInDB: true,
  191. },
  192. {
  193. block: newBlock(header1, commitAtH10),
  194. parts: validPartSet,
  195. seenCommit: seenCommit1,
  196. corruptSeenCommitInDB: true,
  197. wantPanic: "unmarshal to types.Commit failed",
  198. },
  199. {
  200. block: newBlock(header1, commitAtH10),
  201. parts: validPartSet,
  202. seenCommit: seenCommit1,
  203. // Expecting no error and we want a nil back
  204. eraseCommitInDB: true,
  205. },
  206. }
  207. type quad struct {
  208. block *types.Block
  209. commit *types.Commit
  210. meta *types.BlockMeta
  211. seenCommit *types.Commit
  212. }
  213. for i, tuple := range tuples {
  214. tuple := tuple
  215. bs, db := freshBlockStore()
  216. // SaveBlock
  217. res, err, panicErr := doFn(func() (interface{}, error) {
  218. bs.SaveBlock(tuple.block, tuple.parts, tuple.seenCommit)
  219. if tuple.block == nil {
  220. return nil, nil
  221. }
  222. if tuple.corruptBlockInDB {
  223. db.Set(calcBlockMetaKey(tuple.block.Height), []byte("block-bogus"))
  224. }
  225. bBlock := bs.LoadBlock(tuple.block.Height)
  226. bBlockMeta := bs.LoadBlockMeta(tuple.block.Height)
  227. if tuple.eraseSeenCommitInDB {
  228. db.Delete(calcSeenCommitKey(tuple.block.Height))
  229. }
  230. if tuple.corruptSeenCommitInDB {
  231. db.Set(calcSeenCommitKey(tuple.block.Height), []byte("bogus-seen-commit"))
  232. }
  233. bSeenCommit := bs.LoadSeenCommit(tuple.block.Height)
  234. commitHeight := tuple.block.Height - 1
  235. if tuple.eraseCommitInDB {
  236. db.Delete(calcBlockCommitKey(commitHeight))
  237. }
  238. if tuple.corruptCommitInDB {
  239. db.Set(calcBlockCommitKey(commitHeight), []byte("foo-bogus"))
  240. }
  241. bCommit := bs.LoadBlockCommit(commitHeight)
  242. return &quad{block: bBlock, seenCommit: bSeenCommit, commit: bCommit,
  243. meta: bBlockMeta}, nil
  244. })
  245. if subStr := tuple.wantPanic; subStr != "" {
  246. if panicErr == nil {
  247. t.Errorf("#%d: want a non-nil panic", i)
  248. } else if got := fmt.Sprintf("%#v", panicErr); !strings.Contains(got, subStr) {
  249. t.Errorf("#%d:\n\tgotErr: %q\nwant substring: %q", i, got, subStr)
  250. }
  251. continue
  252. }
  253. if tuple.wantErr {
  254. if err == nil {
  255. t.Errorf("#%d: got nil error", i)
  256. }
  257. continue
  258. }
  259. assert.Nil(t, panicErr, "#%d: unexpected panic", i)
  260. assert.Nil(t, err, "#%d: expecting a non-nil error", i)
  261. qua, ok := res.(*quad)
  262. if !ok || qua == nil {
  263. t.Errorf("#%d: got nil quad back; gotType=%T", i, res)
  264. continue
  265. }
  266. if tuple.eraseSeenCommitInDB {
  267. assert.Nil(t, qua.seenCommit,
  268. "erased the seenCommit in the DB hence we should get back a nil seenCommit")
  269. }
  270. if tuple.eraseCommitInDB {
  271. assert.Nil(t, qua.commit,
  272. "erased the commit in the DB hence we should get back a nil commit")
  273. }
  274. }
  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. db.Set(calcBlockPartKey(height, index), []byte("Tendermint"))
  290. res, _, panicErr = doFn(loadPart)
  291. require.NotNil(t, panicErr, "expecting a non-nil panic")
  292. require.Contains(t, panicErr.Error(), "unmarshal to types.Part failed")
  293. // 3. A good block serialized and saved to the DB should be retrievable
  294. db.Set(calcBlockPartKey(height, index), cdc.MustMarshalBinaryBare(part1))
  295. gotPart, _, panicErr := doFn(loadPart)
  296. require.Nil(t, panicErr, "an existent and proper block should not panic")
  297. require.Nil(t, res, "a properly saved block should return a proper block")
  298. require.Equal(t, gotPart.(*types.Part), part1,
  299. "expecting successful retrieval of previously saved block")
  300. }
  301. func TestLoadBlockMeta(t *testing.T) {
  302. bs, db := freshBlockStore()
  303. height := int64(10)
  304. loadMeta := func() (interface{}, error) {
  305. meta := bs.LoadBlockMeta(height)
  306. return meta, nil
  307. }
  308. // Initially no contents.
  309. // 1. Requesting for a non-existent blockMeta shouldn't fail
  310. res, _, panicErr := doFn(loadMeta)
  311. require.Nil(t, panicErr, "a non-existent blockMeta shouldn't cause a panic")
  312. require.Nil(t, res, "a non-existent blockMeta should return nil")
  313. // 2. Next save a corrupted blockMeta then try to load it
  314. db.Set(calcBlockMetaKey(height), []byte("Tendermint-Meta"))
  315. res, _, panicErr = doFn(loadMeta)
  316. require.NotNil(t, panicErr, "expecting a non-nil panic")
  317. require.Contains(t, panicErr.Error(), "unmarshal to types.BlockMeta")
  318. // 3. A good blockMeta serialized and saved to the DB should be retrievable
  319. meta := &types.BlockMeta{}
  320. db.Set(calcBlockMetaKey(height), cdc.MustMarshalBinaryBare(meta))
  321. gotMeta, _, panicErr := doFn(loadMeta)
  322. require.Nil(t, panicErr, "an existent and proper block should not panic")
  323. require.Nil(t, res, "a properly saved blockMeta should return a proper blocMeta ")
  324. require.Equal(t, cdc.MustMarshalBinaryBare(meta), cdc.MustMarshalBinaryBare(gotMeta),
  325. "expecting successful retrieval of previously saved blockMeta")
  326. }
  327. func TestBlockFetchAtHeight(t *testing.T) {
  328. state, bs, cleanup := makeStateAndBlockStore(log.NewTMLogger(new(bytes.Buffer)))
  329. defer cleanup()
  330. require.Equal(t, bs.Height(), int64(0), "initially the height should be zero")
  331. block := makeBlock(bs.Height()+1, state, new(types.Commit))
  332. partSet := block.MakePartSet(2)
  333. seenCommit := makeTestCommit(10, tmtime.Now())
  334. bs.SaveBlock(block, partSet, seenCommit)
  335. require.Equal(t, bs.Height(), block.Header.Height, "expecting the new height to be changed")
  336. blockAtHeight := bs.LoadBlock(bs.Height())
  337. bz1 := cdc.MustMarshalBinaryBare(block)
  338. bz2 := cdc.MustMarshalBinaryBare(blockAtHeight)
  339. require.Equal(t, bz1, bz2)
  340. require.Equal(t, block.Hash(), blockAtHeight.Hash(),
  341. "expecting a successful load of the last saved block")
  342. blockAtHeightPlus1 := bs.LoadBlock(bs.Height() + 1)
  343. require.Nil(t, blockAtHeightPlus1, "expecting an unsuccessful load of Height()+1")
  344. blockAtHeightPlus2 := bs.LoadBlock(bs.Height() + 2)
  345. require.Nil(t, blockAtHeightPlus2, "expecting an unsuccessful load of Height()+2")
  346. }
  347. func doFn(fn func() (interface{}, error)) (res interface{}, err error, panicErr error) {
  348. defer func() {
  349. if r := recover(); r != nil {
  350. switch e := r.(type) {
  351. case error:
  352. panicErr = e
  353. case string:
  354. panicErr = fmt.Errorf("%s", e)
  355. default:
  356. if st, ok := r.(fmt.Stringer); ok {
  357. panicErr = fmt.Errorf("%s", st)
  358. } else {
  359. panicErr = fmt.Errorf("%s", debug.Stack())
  360. }
  361. }
  362. }
  363. }()
  364. res, err = fn()
  365. return res, err, panicErr
  366. }
  367. func newBlock(hdr types.Header, lastCommit *types.Commit) *types.Block {
  368. return &types.Block{
  369. Header: hdr,
  370. LastCommit: lastCommit,
  371. }
  372. }