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.

938 lines
29 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
  1. package v1
  2. import (
  3. "fmt"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. cmn "github.com/tendermint/tendermint/libs/common"
  8. "github.com/tendermint/tendermint/libs/log"
  9. "github.com/tendermint/tendermint/p2p"
  10. "github.com/tendermint/tendermint/types"
  11. )
  12. type lastBlockRequestT struct {
  13. peerID p2p.ID
  14. height int64
  15. }
  16. type lastPeerErrorT struct {
  17. peerID p2p.ID
  18. err error
  19. }
  20. // reactor for FSM testing
  21. type testReactor struct {
  22. logger log.Logger
  23. fsm *BcReactorFSM
  24. numStatusRequests int
  25. numBlockRequests int
  26. lastBlockRequest lastBlockRequestT
  27. lastPeerError lastPeerErrorT
  28. stateTimerStarts map[string]int
  29. }
  30. func sendEventToFSM(fsm *BcReactorFSM, ev bReactorEvent, data bReactorEventData) error {
  31. return fsm.Handle(&bcReactorMessage{event: ev, data: data})
  32. }
  33. type fsmStepTestValues struct {
  34. currentState string
  35. event bReactorEvent
  36. data bReactorEventData
  37. wantErr error
  38. wantState string
  39. wantStatusReqSent bool
  40. wantReqIncreased bool
  41. wantNewBlocks []int64
  42. wantRemovedPeers []p2p.ID
  43. }
  44. // ---------------------------------------------------------------------------
  45. // helper test function for different FSM events, state and expected behavior
  46. func sStopFSMEv(current, expected string) fsmStepTestValues {
  47. return fsmStepTestValues{
  48. currentState: current,
  49. event: stopFSMEv,
  50. wantState: expected,
  51. wantErr: errNoErrorFinished}
  52. }
  53. func sUnknownFSMEv(current string) fsmStepTestValues {
  54. return fsmStepTestValues{
  55. currentState: current,
  56. event: 1234,
  57. wantState: current,
  58. wantErr: errInvalidEvent}
  59. }
  60. func sStartFSMEv() fsmStepTestValues {
  61. return fsmStepTestValues{
  62. currentState: "unknown",
  63. event: startFSMEv,
  64. wantState: "waitForPeer",
  65. wantStatusReqSent: true}
  66. }
  67. func sStateTimeoutEv(current, expected string, timedoutState string, wantErr error) fsmStepTestValues {
  68. return fsmStepTestValues{
  69. currentState: current,
  70. event: stateTimeoutEv,
  71. data: bReactorEventData{
  72. stateName: timedoutState,
  73. },
  74. wantState: expected,
  75. wantErr: wantErr,
  76. }
  77. }
  78. func sProcessedBlockEv(current, expected string, reactorError error) fsmStepTestValues {
  79. return fsmStepTestValues{
  80. currentState: current,
  81. event: processedBlockEv,
  82. data: bReactorEventData{
  83. err: reactorError,
  84. },
  85. wantState: expected,
  86. wantErr: reactorError,
  87. }
  88. }
  89. func sStatusEv(current, expected string, peerID p2p.ID, height int64, err error) fsmStepTestValues {
  90. return fsmStepTestValues{
  91. currentState: current,
  92. event: statusResponseEv,
  93. data: bReactorEventData{peerID: peerID, height: height},
  94. wantState: expected,
  95. wantErr: err}
  96. }
  97. func sMakeRequestsEv(current, expected string, maxPendingRequests int) fsmStepTestValues {
  98. return fsmStepTestValues{
  99. currentState: current,
  100. event: makeRequestsEv,
  101. data: bReactorEventData{maxNumRequests: maxPendingRequests},
  102. wantState: expected,
  103. wantReqIncreased: true,
  104. }
  105. }
  106. func sMakeRequestsEvErrored(current, expected string,
  107. maxPendingRequests int, err error, peersRemoved []p2p.ID) fsmStepTestValues {
  108. return fsmStepTestValues{
  109. currentState: current,
  110. event: makeRequestsEv,
  111. data: bReactorEventData{maxNumRequests: maxPendingRequests},
  112. wantState: expected,
  113. wantErr: err,
  114. wantRemovedPeers: peersRemoved,
  115. wantReqIncreased: true,
  116. }
  117. }
  118. func sBlockRespEv(current, expected string, peerID p2p.ID, height int64, prevBlocks []int64) fsmStepTestValues {
  119. txs := []types.Tx{types.Tx("foo"), types.Tx("bar")}
  120. return fsmStepTestValues{
  121. currentState: current,
  122. event: blockResponseEv,
  123. data: bReactorEventData{
  124. peerID: peerID,
  125. height: height,
  126. block: types.MakeBlock(int64(height), txs, nil, nil),
  127. length: 100},
  128. wantState: expected,
  129. wantNewBlocks: append(prevBlocks, height),
  130. }
  131. }
  132. func sBlockRespEvErrored(current, expected string,
  133. peerID p2p.ID, height int64, prevBlocks []int64, wantErr error, peersRemoved []p2p.ID) fsmStepTestValues {
  134. txs := []types.Tx{types.Tx("foo"), types.Tx("bar")}
  135. return fsmStepTestValues{
  136. currentState: current,
  137. event: blockResponseEv,
  138. data: bReactorEventData{
  139. peerID: peerID,
  140. height: height,
  141. block: types.MakeBlock(int64(height), txs, nil, nil),
  142. length: 100},
  143. wantState: expected,
  144. wantErr: wantErr,
  145. wantRemovedPeers: peersRemoved,
  146. wantNewBlocks: prevBlocks,
  147. }
  148. }
  149. func sPeerRemoveEv(current, expected string, peerID p2p.ID, err error, peersRemoved []p2p.ID) fsmStepTestValues {
  150. return fsmStepTestValues{
  151. currentState: current,
  152. event: peerRemoveEv,
  153. data: bReactorEventData{
  154. peerID: peerID,
  155. err: err,
  156. },
  157. wantState: expected,
  158. wantRemovedPeers: peersRemoved,
  159. }
  160. }
  161. // --------------------------------------------
  162. func newTestReactor(height int64) *testReactor {
  163. testBcR := &testReactor{logger: log.TestingLogger(), stateTimerStarts: make(map[string]int)}
  164. testBcR.fsm = NewFSM(height, testBcR)
  165. testBcR.fsm.SetLogger(testBcR.logger)
  166. return testBcR
  167. }
  168. func fixBlockResponseEvStep(step *fsmStepTestValues, testBcR *testReactor) {
  169. // There is currently no good way to know to which peer a block request was sent.
  170. // So in some cases where it does not matter, before we simulate a block response
  171. // we cheat and look where it is expected from.
  172. if step.event == blockResponseEv {
  173. height := step.data.height
  174. peerID, ok := testBcR.fsm.pool.blocks[height]
  175. if ok {
  176. step.data.peerID = peerID
  177. }
  178. }
  179. }
  180. type testFields struct {
  181. name string
  182. startingHeight int64
  183. maxRequestsPerPeer int
  184. maxPendingRequests int
  185. steps []fsmStepTestValues
  186. }
  187. func executeFSMTests(t *testing.T, tests []testFields, matchRespToReq bool) {
  188. for _, tt := range tests {
  189. t.Run(tt.name, func(t *testing.T) {
  190. // Create test reactor
  191. testBcR := newTestReactor(tt.startingHeight)
  192. if tt.maxRequestsPerPeer != 0 {
  193. maxRequestsPerPeer = tt.maxRequestsPerPeer
  194. }
  195. for _, step := range tt.steps {
  196. assert.Equal(t, step.currentState, testBcR.fsm.state.name)
  197. var heightBefore int64
  198. if step.event == processedBlockEv && step.data.err == errBlockVerificationFailure {
  199. heightBefore = testBcR.fsm.pool.Height
  200. }
  201. oldNumStatusRequests := testBcR.numStatusRequests
  202. oldNumBlockRequests := testBcR.numBlockRequests
  203. if matchRespToReq {
  204. fixBlockResponseEvStep(&step, testBcR)
  205. }
  206. fsmErr := sendEventToFSM(testBcR.fsm, step.event, step.data)
  207. assert.Equal(t, step.wantErr, fsmErr)
  208. if step.wantStatusReqSent {
  209. assert.Equal(t, oldNumStatusRequests+1, testBcR.numStatusRequests)
  210. } else {
  211. assert.Equal(t, oldNumStatusRequests, testBcR.numStatusRequests)
  212. }
  213. if step.wantReqIncreased {
  214. assert.True(t, oldNumBlockRequests < testBcR.numBlockRequests)
  215. } else {
  216. assert.Equal(t, oldNumBlockRequests, testBcR.numBlockRequests)
  217. }
  218. for _, height := range step.wantNewBlocks {
  219. _, err := testBcR.fsm.pool.BlockAndPeerAtHeight(height)
  220. assert.Nil(t, err)
  221. }
  222. if step.event == processedBlockEv && step.data.err == errBlockVerificationFailure {
  223. heightAfter := testBcR.fsm.pool.Height
  224. assert.Equal(t, heightBefore, heightAfter)
  225. firstAfter, err1 := testBcR.fsm.pool.BlockAndPeerAtHeight(testBcR.fsm.pool.Height)
  226. secondAfter, err2 := testBcR.fsm.pool.BlockAndPeerAtHeight(testBcR.fsm.pool.Height + 1)
  227. assert.NotNil(t, err1)
  228. assert.NotNil(t, err2)
  229. assert.Nil(t, firstAfter)
  230. assert.Nil(t, secondAfter)
  231. }
  232. assert.Equal(t, step.wantState, testBcR.fsm.state.name)
  233. if step.wantState == "finished" {
  234. assert.True(t, testBcR.fsm.isCaughtUp())
  235. }
  236. }
  237. })
  238. }
  239. }
  240. func TestFSMBasic(t *testing.T) {
  241. tests := []testFields{
  242. {
  243. name: "one block, one peer - TS2",
  244. startingHeight: 1,
  245. maxRequestsPerPeer: 2,
  246. steps: []fsmStepTestValues{
  247. sStartFSMEv(),
  248. sStatusEv("waitForPeer", "waitForBlock", "P1", 2, nil),
  249. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  250. sBlockRespEv("waitForBlock", "waitForBlock", "P1", 1, []int64{}),
  251. sBlockRespEv("waitForBlock", "waitForBlock", "P2", 2, []int64{1}),
  252. sProcessedBlockEv("waitForBlock", "finished", nil),
  253. },
  254. },
  255. {
  256. name: "multi block, multi peer - TS2",
  257. startingHeight: 1,
  258. maxRequestsPerPeer: 2,
  259. steps: []fsmStepTestValues{
  260. sStartFSMEv(),
  261. sStatusEv("waitForPeer", "waitForBlock", "P1", 4, nil),
  262. sStatusEv("waitForBlock", "waitForBlock", "P2", 4, nil),
  263. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  264. sBlockRespEv("waitForBlock", "waitForBlock", "P1", 1, []int64{}),
  265. sBlockRespEv("waitForBlock", "waitForBlock", "P1", 2, []int64{1}),
  266. sBlockRespEv("waitForBlock", "waitForBlock", "P2", 3, []int64{1, 2}),
  267. sBlockRespEv("waitForBlock", "waitForBlock", "P2", 4, []int64{1, 2, 3}),
  268. sProcessedBlockEv("waitForBlock", "waitForBlock", nil),
  269. sProcessedBlockEv("waitForBlock", "waitForBlock", nil),
  270. sProcessedBlockEv("waitForBlock", "finished", nil),
  271. },
  272. },
  273. }
  274. executeFSMTests(t, tests, true)
  275. }
  276. func TestFSMBlockVerificationFailure(t *testing.T) {
  277. tests := []testFields{
  278. {
  279. name: "block verification failure - TS2 variant",
  280. startingHeight: 1,
  281. maxRequestsPerPeer: 3,
  282. steps: []fsmStepTestValues{
  283. sStartFSMEv(),
  284. // add P1 and get blocks 1-3 from it
  285. sStatusEv("waitForPeer", "waitForBlock", "P1", 3, nil),
  286. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  287. sBlockRespEv("waitForBlock", "waitForBlock", "P1", 1, []int64{}),
  288. sBlockRespEv("waitForBlock", "waitForBlock", "P1", 2, []int64{1}),
  289. sBlockRespEv("waitForBlock", "waitForBlock", "P1", 3, []int64{1, 2}),
  290. // add P2
  291. sStatusEv("waitForBlock", "waitForBlock", "P2", 3, nil),
  292. // process block failure, should remove P1 and all blocks
  293. sProcessedBlockEv("waitForBlock", "waitForBlock", errBlockVerificationFailure),
  294. // get blocks 1-3 from P2
  295. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  296. sBlockRespEv("waitForBlock", "waitForBlock", "P2", 1, []int64{}),
  297. sBlockRespEv("waitForBlock", "waitForBlock", "P2", 2, []int64{1}),
  298. sBlockRespEv("waitForBlock", "waitForBlock", "P2", 3, []int64{1, 2}),
  299. // finish after processing blocks 1 and 2
  300. sProcessedBlockEv("waitForBlock", "waitForBlock", nil),
  301. sProcessedBlockEv("waitForBlock", "finished", nil),
  302. },
  303. },
  304. }
  305. executeFSMTests(t, tests, false)
  306. }
  307. func TestFSMBadBlockFromPeer(t *testing.T) {
  308. tests := []testFields{
  309. {
  310. name: "block we haven't asked for",
  311. startingHeight: 1,
  312. maxRequestsPerPeer: 3,
  313. steps: []fsmStepTestValues{
  314. sStartFSMEv(),
  315. // add P1 and ask for blocks 1-3
  316. sStatusEv("waitForPeer", "waitForBlock", "P1", 300, nil),
  317. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  318. // blockResponseEv for height 100 should cause an error
  319. sBlockRespEvErrored("waitForBlock", "waitForPeer",
  320. "P1", 100, []int64{}, errMissingBlock, []p2p.ID{}),
  321. },
  322. },
  323. {
  324. name: "block we already have",
  325. startingHeight: 1,
  326. maxRequestsPerPeer: 3,
  327. steps: []fsmStepTestValues{
  328. sStartFSMEv(),
  329. // add P1 and get block 1
  330. sStatusEv("waitForPeer", "waitForBlock", "P1", 100, nil),
  331. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  332. sBlockRespEv("waitForBlock", "waitForBlock",
  333. "P1", 1, []int64{}),
  334. // Get block 1 again. Since peer is removed together with block 1,
  335. // the blocks present in the pool should be {}
  336. sBlockRespEvErrored("waitForBlock", "waitForPeer",
  337. "P1", 1, []int64{}, errDuplicateBlock, []p2p.ID{"P1"}),
  338. },
  339. },
  340. {
  341. name: "block from unknown peer",
  342. startingHeight: 1,
  343. maxRequestsPerPeer: 3,
  344. steps: []fsmStepTestValues{
  345. sStartFSMEv(),
  346. // add P1 and get block 1
  347. sStatusEv("waitForPeer", "waitForBlock", "P1", 3, nil),
  348. // get block 1 from unknown peer P2
  349. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  350. sBlockRespEvErrored("waitForBlock", "waitForBlock",
  351. "P2", 1, []int64{}, errBadDataFromPeer, []p2p.ID{"P2"}),
  352. },
  353. },
  354. {
  355. name: "block from wrong peer",
  356. startingHeight: 1,
  357. maxRequestsPerPeer: 3,
  358. steps: []fsmStepTestValues{
  359. sStartFSMEv(),
  360. // add P1, make requests for blocks 1-3 to P1
  361. sStatusEv("waitForPeer", "waitForBlock", "P1", 3, nil),
  362. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  363. // add P2
  364. sStatusEv("waitForBlock", "waitForBlock", "P2", 3, nil),
  365. // receive block 1 from P2
  366. sBlockRespEvErrored("waitForBlock", "waitForBlock",
  367. "P2", 1, []int64{}, errBadDataFromPeer, []p2p.ID{"P2"}),
  368. },
  369. },
  370. }
  371. executeFSMTests(t, tests, false)
  372. }
  373. func TestFSMBlockAtCurrentHeightDoesNotArriveInTime(t *testing.T) {
  374. tests := []testFields{
  375. {
  376. name: "block at current height undelivered - TS5",
  377. startingHeight: 1,
  378. maxRequestsPerPeer: 3,
  379. steps: []fsmStepTestValues{
  380. sStartFSMEv(),
  381. // add P1, get blocks 1 and 2, process block 1
  382. sStatusEv("waitForPeer", "waitForBlock", "P1", 3, nil),
  383. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  384. sBlockRespEv("waitForBlock", "waitForBlock",
  385. "P1", 1, []int64{}),
  386. sBlockRespEv("waitForBlock", "waitForBlock",
  387. "P1", 2, []int64{1}),
  388. sProcessedBlockEv("waitForBlock", "waitForBlock", nil),
  389. // add P2
  390. sStatusEv("waitForBlock", "waitForBlock", "P2", 3, nil),
  391. // timeout on block 3, P1 should be removed
  392. sStateTimeoutEv("waitForBlock", "waitForBlock", "waitForBlock", errNoPeerResponseForCurrentHeights),
  393. // make requests and finish by receiving blocks 2 and 3 from P2
  394. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  395. sBlockRespEv("waitForBlock", "waitForBlock", "P2", 2, []int64{}),
  396. sBlockRespEv("waitForBlock", "waitForBlock", "P2", 3, []int64{2}),
  397. sProcessedBlockEv("waitForBlock", "finished", nil),
  398. },
  399. },
  400. {
  401. name: "block at current height undelivered, at maxPeerHeight after peer removal - TS3",
  402. startingHeight: 1,
  403. maxRequestsPerPeer: 3,
  404. steps: []fsmStepTestValues{
  405. sStartFSMEv(),
  406. // add P1, request blocks 1-3 from P1
  407. sStatusEv("waitForPeer", "waitForBlock", "P1", 3, nil),
  408. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  409. // add P2 (tallest)
  410. sStatusEv("waitForBlock", "waitForBlock", "P2", 30, nil),
  411. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  412. // receive blocks 1-3 from P1
  413. sBlockRespEv("waitForBlock", "waitForBlock", "P1", 1, []int64{}),
  414. sBlockRespEv("waitForBlock", "waitForBlock", "P1", 2, []int64{1}),
  415. sBlockRespEv("waitForBlock", "waitForBlock", "P1", 3, []int64{1, 2}),
  416. // process blocks at heights 1 and 2
  417. sProcessedBlockEv("waitForBlock", "waitForBlock", nil),
  418. sProcessedBlockEv("waitForBlock", "waitForBlock", nil),
  419. // timeout on block at height 4
  420. sStateTimeoutEv("waitForBlock", "finished", "waitForBlock", nil),
  421. },
  422. },
  423. }
  424. executeFSMTests(t, tests, true)
  425. }
  426. func TestFSMPeerRelatedEvents(t *testing.T) {
  427. tests := []testFields{
  428. {
  429. name: "peer remove event with no blocks",
  430. startingHeight: 1,
  431. steps: []fsmStepTestValues{
  432. sStartFSMEv(),
  433. // add P1, P2, P3
  434. sStatusEv("waitForPeer", "waitForBlock", "P1", 3, nil),
  435. sStatusEv("waitForBlock", "waitForBlock", "P2", 3, nil),
  436. sStatusEv("waitForBlock", "waitForBlock", "P3", 3, nil),
  437. // switch removes P2
  438. sPeerRemoveEv("waitForBlock", "waitForBlock", "P2", errSwitchRemovesPeer, []p2p.ID{"P2"}),
  439. },
  440. },
  441. {
  442. name: "only peer removed while in waitForBlock state",
  443. startingHeight: 100,
  444. steps: []fsmStepTestValues{
  445. sStartFSMEv(),
  446. // add P1
  447. sStatusEv("waitForPeer", "waitForBlock", "P1", 200, nil),
  448. // switch removes P1
  449. sPeerRemoveEv("waitForBlock", "waitForPeer", "P1", errSwitchRemovesPeer, []p2p.ID{"P1"}),
  450. },
  451. },
  452. {
  453. name: "highest peer removed while in waitForBlock state, node reaches maxPeerHeight - TS4 ",
  454. startingHeight: 100,
  455. maxRequestsPerPeer: 3,
  456. steps: []fsmStepTestValues{
  457. sStartFSMEv(),
  458. // add P1 and make requests
  459. sStatusEv("waitForPeer", "waitForBlock", "P1", 101, nil),
  460. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  461. // add P2
  462. sStatusEv("waitForBlock", "waitForBlock", "P2", 200, nil),
  463. // get blocks 100 and 101 from P1 and process block at height 100
  464. sBlockRespEv("waitForBlock", "waitForBlock", "P1", 100, []int64{}),
  465. sBlockRespEv("waitForBlock", "waitForBlock", "P1", 101, []int64{100}),
  466. sProcessedBlockEv("waitForBlock", "waitForBlock", nil),
  467. // switch removes peer P1, should be finished
  468. sPeerRemoveEv("waitForBlock", "finished", "P2", errSwitchRemovesPeer, []p2p.ID{"P2"}),
  469. },
  470. },
  471. {
  472. name: "highest peer lowers its height in waitForBlock state, node reaches maxPeerHeight - TS4",
  473. startingHeight: 100,
  474. maxRequestsPerPeer: 3,
  475. steps: []fsmStepTestValues{
  476. sStartFSMEv(),
  477. // add P1 and make requests
  478. sStatusEv("waitForPeer", "waitForBlock", "P1", 101, nil),
  479. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  480. // add P2
  481. sStatusEv("waitForBlock", "waitForBlock", "P2", 200, nil),
  482. // get blocks 100 and 101 from P1
  483. sBlockRespEv("waitForBlock", "waitForBlock", "P1", 100, []int64{}),
  484. sBlockRespEv("waitForBlock", "waitForBlock", "P1", 101, []int64{100}),
  485. // processed block at heights 100
  486. sProcessedBlockEv("waitForBlock", "waitForBlock", nil),
  487. // P2 becomes short
  488. sStatusEv("waitForBlock", "finished", "P2", 100, errPeerLowersItsHeight),
  489. },
  490. },
  491. {
  492. name: "new short peer while in waitForPeer state",
  493. startingHeight: 100,
  494. steps: []fsmStepTestValues{
  495. sStartFSMEv(),
  496. sStatusEv("waitForPeer", "waitForPeer", "P1", 3, errPeerTooShort),
  497. },
  498. },
  499. {
  500. name: "new short peer while in waitForBlock state",
  501. startingHeight: 100,
  502. steps: []fsmStepTestValues{
  503. sStartFSMEv(),
  504. sStatusEv("waitForPeer", "waitForBlock", "P1", 200, nil),
  505. sStatusEv("waitForBlock", "waitForBlock", "P2", 3, errPeerTooShort),
  506. },
  507. },
  508. {
  509. name: "only peer updated with low height while in waitForBlock state",
  510. startingHeight: 100,
  511. steps: []fsmStepTestValues{
  512. sStartFSMEv(),
  513. sStatusEv("waitForPeer", "waitForBlock", "P1", 200, nil),
  514. sStatusEv("waitForBlock", "waitForPeer", "P1", 3, errPeerLowersItsHeight),
  515. },
  516. },
  517. {
  518. name: "peer does not exist in the switch",
  519. startingHeight: 9999999,
  520. maxRequestsPerPeer: 3,
  521. steps: []fsmStepTestValues{
  522. sStartFSMEv(),
  523. // add P1
  524. sStatusEv("waitForPeer", "waitForBlock", "P1", 20000000, nil),
  525. // send request for block 9999999
  526. // Note: For this block request the "switch missing the peer" error is simulated,
  527. // see implementation of bcReactor interface, sendBlockRequest(), in this file.
  528. sMakeRequestsEvErrored("waitForBlock", "waitForBlock",
  529. maxNumRequests, nil, []p2p.ID{"P1"}),
  530. },
  531. },
  532. }
  533. executeFSMTests(t, tests, true)
  534. }
  535. func TestFSMStopFSM(t *testing.T) {
  536. tests := []testFields{
  537. {
  538. name: "stopFSMEv in unknown",
  539. steps: []fsmStepTestValues{
  540. sStopFSMEv("unknown", "finished"),
  541. },
  542. },
  543. {
  544. name: "stopFSMEv in waitForPeer",
  545. startingHeight: 1,
  546. steps: []fsmStepTestValues{
  547. sStartFSMEv(),
  548. sStopFSMEv("waitForPeer", "finished"),
  549. },
  550. },
  551. {
  552. name: "stopFSMEv in waitForBlock",
  553. startingHeight: 1,
  554. steps: []fsmStepTestValues{
  555. sStartFSMEv(),
  556. sStatusEv("waitForPeer", "waitForBlock", "P1", 3, nil),
  557. sStopFSMEv("waitForBlock", "finished"),
  558. },
  559. },
  560. }
  561. executeFSMTests(t, tests, false)
  562. }
  563. func TestFSMUnknownElements(t *testing.T) {
  564. tests := []testFields{
  565. {
  566. name: "unknown event for state unknown",
  567. steps: []fsmStepTestValues{
  568. sUnknownFSMEv("unknown"),
  569. },
  570. },
  571. {
  572. name: "unknown event for state waitForPeer",
  573. steps: []fsmStepTestValues{
  574. sStartFSMEv(),
  575. sUnknownFSMEv("waitForPeer"),
  576. },
  577. },
  578. {
  579. name: "unknown event for state waitForBlock",
  580. startingHeight: 1,
  581. steps: []fsmStepTestValues{
  582. sStartFSMEv(),
  583. sStatusEv("waitForPeer", "waitForBlock", "P1", 3, nil),
  584. sUnknownFSMEv("waitForBlock"),
  585. },
  586. },
  587. }
  588. executeFSMTests(t, tests, false)
  589. }
  590. func TestFSMPeerStateTimeoutEvent(t *testing.T) {
  591. tests := []testFields{
  592. {
  593. name: "timeout event for state waitForPeer while in state waitForPeer - TS1",
  594. startingHeight: 1,
  595. maxRequestsPerPeer: 3,
  596. steps: []fsmStepTestValues{
  597. sStartFSMEv(),
  598. sStateTimeoutEv("waitForPeer", "finished", "waitForPeer", errNoTallerPeer),
  599. },
  600. },
  601. {
  602. name: "timeout event for state waitForPeer while in a state != waitForPeer",
  603. startingHeight: 1,
  604. maxRequestsPerPeer: 3,
  605. steps: []fsmStepTestValues{
  606. sStartFSMEv(),
  607. sStateTimeoutEv("waitForPeer", "waitForPeer", "waitForBlock", errTimeoutEventWrongState),
  608. },
  609. },
  610. {
  611. name: "timeout event for state waitForBlock while in state waitForBlock ",
  612. startingHeight: 1,
  613. maxRequestsPerPeer: 3,
  614. steps: []fsmStepTestValues{
  615. sStartFSMEv(),
  616. sStatusEv("waitForPeer", "waitForBlock", "P1", 3, nil),
  617. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  618. sStateTimeoutEv("waitForBlock", "waitForPeer", "waitForBlock", errNoPeerResponseForCurrentHeights),
  619. },
  620. },
  621. {
  622. name: "timeout event for state waitForBlock while in a state != waitForBlock",
  623. startingHeight: 1,
  624. maxRequestsPerPeer: 3,
  625. steps: []fsmStepTestValues{
  626. sStartFSMEv(),
  627. sStatusEv("waitForPeer", "waitForBlock", "P1", 3, nil),
  628. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  629. sStateTimeoutEv("waitForBlock", "waitForBlock", "waitForPeer", errTimeoutEventWrongState),
  630. },
  631. },
  632. {
  633. name: "timeout event for state waitForBlock with multiple peers",
  634. startingHeight: 1,
  635. maxRequestsPerPeer: 3,
  636. steps: []fsmStepTestValues{
  637. sStartFSMEv(),
  638. sStatusEv("waitForPeer", "waitForBlock", "P1", 3, nil),
  639. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  640. sStatusEv("waitForBlock", "waitForBlock", "P2", 3, nil),
  641. sStateTimeoutEv("waitForBlock", "waitForBlock", "waitForBlock", errNoPeerResponseForCurrentHeights),
  642. },
  643. },
  644. }
  645. executeFSMTests(t, tests, false)
  646. }
  647. func makeCorrectTransitionSequence(startingHeight int64, numBlocks int64, numPeers int, randomPeerHeights bool,
  648. maxRequestsPerPeer int, maxPendingRequests int) testFields {
  649. // Generate numPeers peers with random or numBlocks heights according to the randomPeerHeights flag.
  650. peerHeights := make([]int64, numPeers)
  651. for i := 0; i < numPeers; i++ {
  652. if i == 0 {
  653. peerHeights[0] = numBlocks
  654. continue
  655. }
  656. if randomPeerHeights {
  657. peerHeights[i] = int64(cmn.MaxInt(cmn.RandIntn(int(numBlocks)), int(startingHeight)+1))
  658. } else {
  659. peerHeights[i] = numBlocks
  660. }
  661. }
  662. // Approximate the slice capacity to save time for appends.
  663. testSteps := make([]fsmStepTestValues, 0, 3*numBlocks+int64(numPeers))
  664. testName := fmt.Sprintf("%v-blocks %v-startingHeight %v-peers %v-maxRequestsPerPeer %v-maxNumRequests",
  665. numBlocks, startingHeight, numPeers, maxRequestsPerPeer, maxPendingRequests)
  666. // Add startFSMEv step.
  667. testSteps = append(testSteps, sStartFSMEv())
  668. // For each peer, add statusResponseEv step.
  669. for i := 0; i < numPeers; i++ {
  670. peerName := fmt.Sprintf("P%d", i)
  671. if i == 0 {
  672. testSteps = append(
  673. testSteps,
  674. sStatusEv("waitForPeer", "waitForBlock", p2p.ID(peerName), peerHeights[i], nil))
  675. } else {
  676. testSteps = append(testSteps,
  677. sStatusEv("waitForBlock", "waitForBlock", p2p.ID(peerName), peerHeights[i], nil))
  678. }
  679. }
  680. height := startingHeight
  681. numBlocksReceived := 0
  682. prevBlocks := make([]int64, 0, maxPendingRequests)
  683. forLoop:
  684. for i := 0; i < int(numBlocks); i++ {
  685. // Add the makeRequestEv step periodically.
  686. if i%int(maxRequestsPerPeer) == 0 {
  687. testSteps = append(
  688. testSteps,
  689. sMakeRequestsEv("waitForBlock", "waitForBlock", maxNumRequests),
  690. )
  691. }
  692. // Add the blockRespEv step
  693. testSteps = append(
  694. testSteps,
  695. sBlockRespEv("waitForBlock", "waitForBlock",
  696. "P0", height, prevBlocks))
  697. prevBlocks = append(prevBlocks, height)
  698. height++
  699. numBlocksReceived++
  700. // Add the processedBlockEv step periodically.
  701. if numBlocksReceived >= int(maxRequestsPerPeer) || height >= numBlocks {
  702. for j := int(height) - numBlocksReceived; j < int(height); j++ {
  703. if j >= int(numBlocks) {
  704. // This is the last block that is processed, we should be in "finished" state.
  705. testSteps = append(
  706. testSteps,
  707. sProcessedBlockEv("waitForBlock", "finished", nil))
  708. break forLoop
  709. }
  710. testSteps = append(
  711. testSteps,
  712. sProcessedBlockEv("waitForBlock", "waitForBlock", nil))
  713. }
  714. numBlocksReceived = 0
  715. prevBlocks = make([]int64, 0, maxPendingRequests)
  716. }
  717. }
  718. return testFields{
  719. name: testName,
  720. startingHeight: startingHeight,
  721. maxRequestsPerPeer: maxRequestsPerPeer,
  722. maxPendingRequests: maxPendingRequests,
  723. steps: testSteps,
  724. }
  725. }
  726. const (
  727. maxStartingHeightTest = 100
  728. maxRequestsPerPeerTest = 20
  729. maxTotalPendingRequestsTest = 600
  730. maxNumPeersTest = 1000
  731. maxNumBlocksInChainTest = 10000 //should be smaller than 9999999
  732. )
  733. func makeCorrectTransitionSequenceWithRandomParameters() testFields {
  734. // Generate a starting height for fast sync.
  735. startingHeight := int64(cmn.RandIntn(maxStartingHeightTest) + 1)
  736. // Generate the number of requests per peer.
  737. maxRequestsPerPeer := cmn.RandIntn(maxRequestsPerPeerTest) + 1
  738. // Generate the maximum number of total pending requests, >= maxRequestsPerPeer.
  739. maxPendingRequests := cmn.RandIntn(maxTotalPendingRequestsTest-int(maxRequestsPerPeer)) + maxRequestsPerPeer
  740. // Generate the number of blocks to be synced.
  741. numBlocks := int64(cmn.RandIntn(maxNumBlocksInChainTest)) + startingHeight
  742. // Generate a number of peers.
  743. numPeers := cmn.RandIntn(maxNumPeersTest) + 1
  744. return makeCorrectTransitionSequence(startingHeight, numBlocks, numPeers, true, maxRequestsPerPeer, maxPendingRequests)
  745. }
  746. func shouldApplyProcessedBlockEvStep(step *fsmStepTestValues, testBcR *testReactor) bool {
  747. if step.event == processedBlockEv {
  748. _, err := testBcR.fsm.pool.BlockAndPeerAtHeight(testBcR.fsm.pool.Height)
  749. if err == errMissingBlock {
  750. return false
  751. }
  752. _, err = testBcR.fsm.pool.BlockAndPeerAtHeight(testBcR.fsm.pool.Height + 1)
  753. if err == errMissingBlock {
  754. return false
  755. }
  756. }
  757. return true
  758. }
  759. func TestFSMCorrectTransitionSequences(t *testing.T) {
  760. tests := []testFields{
  761. makeCorrectTransitionSequence(1, 100, 10, true, 10, 40),
  762. makeCorrectTransitionSequenceWithRandomParameters(),
  763. }
  764. for _, tt := range tests {
  765. t.Run(tt.name, func(t *testing.T) {
  766. // Create test reactor
  767. testBcR := newTestReactor(tt.startingHeight)
  768. if tt.maxRequestsPerPeer != 0 {
  769. maxRequestsPerPeer = tt.maxRequestsPerPeer
  770. }
  771. for _, step := range tt.steps {
  772. assert.Equal(t, step.currentState, testBcR.fsm.state.name)
  773. oldNumStatusRequests := testBcR.numStatusRequests
  774. fixBlockResponseEvStep(&step, testBcR)
  775. if !shouldApplyProcessedBlockEvStep(&step, testBcR) {
  776. continue
  777. }
  778. fsmErr := sendEventToFSM(testBcR.fsm, step.event, step.data)
  779. assert.Equal(t, step.wantErr, fsmErr)
  780. if step.wantStatusReqSent {
  781. assert.Equal(t, oldNumStatusRequests+1, testBcR.numStatusRequests)
  782. } else {
  783. assert.Equal(t, oldNumStatusRequests, testBcR.numStatusRequests)
  784. }
  785. assert.Equal(t, step.wantState, testBcR.fsm.state.name)
  786. if step.wantState == "finished" {
  787. assert.True(t, testBcR.fsm.isCaughtUp())
  788. }
  789. }
  790. })
  791. }
  792. }
  793. // ----------------------------------------
  794. // implements the bcRNotifier
  795. func (testR *testReactor) sendPeerError(err error, peerID p2p.ID) {
  796. testR.logger.Info("Reactor received sendPeerError call from FSM", "peer", peerID, "err", err)
  797. testR.lastPeerError.peerID = peerID
  798. testR.lastPeerError.err = err
  799. }
  800. func (testR *testReactor) sendStatusRequest() {
  801. testR.logger.Info("Reactor received sendStatusRequest call from FSM")
  802. testR.numStatusRequests++
  803. }
  804. func (testR *testReactor) sendBlockRequest(peerID p2p.ID, height int64) error {
  805. testR.logger.Info("Reactor received sendBlockRequest call from FSM", "peer", peerID, "height", height)
  806. testR.numBlockRequests++
  807. testR.lastBlockRequest.peerID = peerID
  808. testR.lastBlockRequest.height = height
  809. if height == 9999999 {
  810. // simulate switch does not have peer
  811. return errNilPeerForBlockRequest
  812. }
  813. return nil
  814. }
  815. func (testR *testReactor) resetStateTimer(name string, timer **time.Timer, timeout time.Duration) {
  816. testR.logger.Info("Reactor received resetStateTimer call from FSM", "state", name, "timeout", timeout)
  817. if _, ok := testR.stateTimerStarts[name]; !ok {
  818. testR.stateTimerStarts[name] = 1
  819. } else {
  820. testR.stateTimerStarts[name]++
  821. }
  822. }
  823. func (testR *testReactor) switchToConsensus() {
  824. }
  825. // ----------------------------------------