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.

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