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.

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