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.

450 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
  1. package v1
  2. import (
  3. "errors"
  4. "fmt"
  5. "sync"
  6. "time"
  7. "github.com/tendermint/tendermint/libs/log"
  8. "github.com/tendermint/tendermint/p2p"
  9. "github.com/tendermint/tendermint/types"
  10. )
  11. // Blockchain Reactor State
  12. type bcReactorFSMState struct {
  13. name string
  14. // called when transitioning out of current state
  15. handle func(*BcReactorFSM, bReactorEvent, bReactorEventData) (next *bcReactorFSMState, err error)
  16. // called when entering the state
  17. enter func(fsm *BcReactorFSM)
  18. // timeout to ensure FSM is not stuck in a state forever
  19. // the timer is owned and run by the fsm instance
  20. timeout time.Duration
  21. }
  22. func (s *bcReactorFSMState) String() string {
  23. return s.name
  24. }
  25. // BcReactorFSM is the datastructure for the Blockchain Reactor State Machine
  26. type BcReactorFSM struct {
  27. logger log.Logger
  28. mtx sync.Mutex
  29. startTime time.Time
  30. state *bcReactorFSMState
  31. stateTimer *time.Timer
  32. pool *BlockPool
  33. // interface used to call the Blockchain reactor to send StatusRequest, BlockRequest, reporting errors, etc.
  34. toBcR bcReactor
  35. }
  36. // NewFSM creates a new reactor FSM.
  37. func NewFSM(height int64, toBcR bcReactor) *BcReactorFSM {
  38. return &BcReactorFSM{
  39. state: unknown,
  40. startTime: time.Now(),
  41. pool: NewBlockPool(height, toBcR),
  42. toBcR: toBcR,
  43. }
  44. }
  45. // bReactorEventData is part of the message sent by the reactor to the FSM and used by the state handlers.
  46. type bReactorEventData struct {
  47. peerID p2p.ID
  48. err error // for peer error: timeout, slow; for processed block event if error occurred
  49. height int64 // for status response; for processed block event
  50. block *types.Block // for block response
  51. stateName string // for state timeout events
  52. length int // for block response event, length of received block, used to detect slow peers
  53. maxNumRequests int // for request needed event, maximum number of pending requests
  54. }
  55. // Blockchain Reactor Events (the input to the state machine)
  56. type bReactorEvent uint
  57. const (
  58. // message type events
  59. startFSMEv = iota + 1
  60. statusResponseEv
  61. blockResponseEv
  62. processedBlockEv
  63. makeRequestsEv
  64. stopFSMEv
  65. // other events
  66. peerRemoveEv = iota + 256
  67. stateTimeoutEv
  68. )
  69. func (msg *bcReactorMessage) String() string {
  70. var dataStr string
  71. switch msg.event {
  72. case startFSMEv:
  73. dataStr = ""
  74. case statusResponseEv:
  75. dataStr = fmt.Sprintf("peer=%v height=%v", msg.data.peerID, msg.data.height)
  76. case blockResponseEv:
  77. dataStr = fmt.Sprintf("peer=%v block.height=%v length=%v",
  78. msg.data.peerID, msg.data.block.Height, msg.data.length)
  79. case processedBlockEv:
  80. dataStr = fmt.Sprintf("error=%v", msg.data.err)
  81. case makeRequestsEv:
  82. dataStr = ""
  83. case stopFSMEv:
  84. dataStr = ""
  85. case peerRemoveEv:
  86. dataStr = fmt.Sprintf("peer: %v is being removed by the switch", msg.data.peerID)
  87. case stateTimeoutEv:
  88. dataStr = fmt.Sprintf("state=%v", msg.data.stateName)
  89. default:
  90. dataStr = fmt.Sprintf("cannot interpret message data")
  91. }
  92. return fmt.Sprintf("%v: %v", msg.event, dataStr)
  93. }
  94. func (ev bReactorEvent) String() string {
  95. switch ev {
  96. case startFSMEv:
  97. return "startFSMEv"
  98. case statusResponseEv:
  99. return "statusResponseEv"
  100. case blockResponseEv:
  101. return "blockResponseEv"
  102. case processedBlockEv:
  103. return "processedBlockEv"
  104. case makeRequestsEv:
  105. return "makeRequestsEv"
  106. case stopFSMEv:
  107. return "stopFSMEv"
  108. case peerRemoveEv:
  109. return "peerRemoveEv"
  110. case stateTimeoutEv:
  111. return "stateTimeoutEv"
  112. default:
  113. return "event unknown"
  114. }
  115. }
  116. // states
  117. var (
  118. unknown *bcReactorFSMState
  119. waitForPeer *bcReactorFSMState
  120. waitForBlock *bcReactorFSMState
  121. finished *bcReactorFSMState
  122. )
  123. // timeouts for state timers
  124. const (
  125. waitForPeerTimeout = 3 * time.Second
  126. waitForBlockAtCurrentHeightTimeout = 10 * time.Second
  127. )
  128. // errors
  129. var (
  130. // internal to the package
  131. errNoErrorFinished = errors.New("fast sync is finished")
  132. errInvalidEvent = errors.New("invalid event in current state")
  133. errMissingBlock = errors.New("missing blocks")
  134. errNilPeerForBlockRequest = errors.New("peer for block request does not exist in the switch")
  135. errSendQueueFull = errors.New("block request not made, send-queue is full")
  136. errPeerTooShort = errors.New("peer height too low, old peer removed/ new peer not added")
  137. errSwitchRemovesPeer = errors.New("switch is removing peer")
  138. errTimeoutEventWrongState = errors.New("timeout event for a state different than the current one")
  139. errNoTallerPeer = errors.New("fast sync timed out on waiting for a peer taller than this node")
  140. // reported eventually to the switch
  141. errPeerLowersItsHeight = errors.New("fast sync peer reports a height lower than previous") // handle return
  142. errNoPeerResponseForCurrentHeights = errors.New("fast sync timed out on peer block response for current heights") // handle return
  143. errNoPeerResponse = errors.New("fast sync timed out on peer block response") // xx
  144. errBadDataFromPeer = errors.New("fast sync received block from wrong peer or block is bad") // xx
  145. errDuplicateBlock = errors.New("fast sync received duplicate block from peer")
  146. errBlockVerificationFailure = errors.New("fast sync block verification failure") // xx
  147. errSlowPeer = errors.New("fast sync peer is not sending us data fast enough") // xx
  148. )
  149. func init() {
  150. unknown = &bcReactorFSMState{
  151. name: "unknown",
  152. handle: func(fsm *BcReactorFSM, ev bReactorEvent, data bReactorEventData) (*bcReactorFSMState, error) {
  153. switch ev {
  154. case startFSMEv:
  155. // Broadcast Status message. Currently doesn't return non-nil error.
  156. fsm.toBcR.sendStatusRequest()
  157. return waitForPeer, nil
  158. case stopFSMEv:
  159. return finished, errNoErrorFinished
  160. default:
  161. return unknown, errInvalidEvent
  162. }
  163. },
  164. }
  165. waitForPeer = &bcReactorFSMState{
  166. name: "waitForPeer",
  167. timeout: waitForPeerTimeout,
  168. enter: func(fsm *BcReactorFSM) {
  169. // Stop when leaving the state.
  170. fsm.resetStateTimer()
  171. },
  172. handle: func(fsm *BcReactorFSM, ev bReactorEvent, data bReactorEventData) (*bcReactorFSMState, error) {
  173. switch ev {
  174. case stateTimeoutEv:
  175. if data.stateName != "waitForPeer" {
  176. fsm.logger.Error("received a state timeout event for different state",
  177. "state", data.stateName)
  178. return waitForPeer, errTimeoutEventWrongState
  179. }
  180. // There was no statusResponse received from any peer.
  181. // Should we send status request again?
  182. return finished, errNoTallerPeer
  183. case statusResponseEv:
  184. if err := fsm.pool.UpdatePeer(data.peerID, data.height); err != nil {
  185. if fsm.pool.NumPeers() == 0 {
  186. return waitForPeer, err
  187. }
  188. }
  189. if fsm.stateTimer != nil {
  190. fsm.stateTimer.Stop()
  191. }
  192. return waitForBlock, nil
  193. case stopFSMEv:
  194. if fsm.stateTimer != nil {
  195. fsm.stateTimer.Stop()
  196. }
  197. return finished, errNoErrorFinished
  198. default:
  199. return waitForPeer, errInvalidEvent
  200. }
  201. },
  202. }
  203. waitForBlock = &bcReactorFSMState{
  204. name: "waitForBlock",
  205. timeout: waitForBlockAtCurrentHeightTimeout,
  206. enter: func(fsm *BcReactorFSM) {
  207. // Stop when leaving the state.
  208. fsm.resetStateTimer()
  209. },
  210. handle: func(fsm *BcReactorFSM, ev bReactorEvent, data bReactorEventData) (*bcReactorFSMState, error) {
  211. switch ev {
  212. case statusResponseEv:
  213. err := fsm.pool.UpdatePeer(data.peerID, data.height)
  214. if fsm.pool.NumPeers() == 0 {
  215. return waitForPeer, err
  216. }
  217. if fsm.pool.ReachedMaxHeight() {
  218. return finished, err
  219. }
  220. return waitForBlock, err
  221. case blockResponseEv:
  222. fsm.logger.Debug("blockResponseEv", "H", data.block.Height)
  223. err := fsm.pool.AddBlock(data.peerID, data.block, data.length)
  224. if err != nil {
  225. // A block was received that was unsolicited, from unexpected peer, or that we already have it.
  226. // Ignore block, remove peer and send error to switch.
  227. fsm.pool.RemovePeer(data.peerID, err)
  228. fsm.toBcR.sendPeerError(err, data.peerID)
  229. }
  230. if fsm.pool.NumPeers() == 0 {
  231. return waitForPeer, err
  232. }
  233. return waitForBlock, err
  234. case processedBlockEv:
  235. if data.err != nil {
  236. first, second, _ := fsm.pool.FirstTwoBlocksAndPeers()
  237. fsm.logger.Error("error processing block", "err", data.err,
  238. "first", first.block.Height, "second", second.block.Height)
  239. fsm.logger.Error("send peer error for", "peer", first.peer.ID)
  240. fsm.toBcR.sendPeerError(data.err, first.peer.ID)
  241. fsm.logger.Error("send peer error for", "peer", second.peer.ID)
  242. fsm.toBcR.sendPeerError(data.err, second.peer.ID)
  243. // Remove the first two blocks. This will also remove the peers
  244. fsm.pool.InvalidateFirstTwoBlocks(data.err)
  245. } else {
  246. fsm.pool.ProcessedCurrentHeightBlock()
  247. // Since we advanced one block reset the state timer
  248. fsm.resetStateTimer()
  249. }
  250. // Both cases above may result in achieving maximum height.
  251. if fsm.pool.ReachedMaxHeight() {
  252. return finished, nil
  253. }
  254. return waitForBlock, data.err
  255. case peerRemoveEv:
  256. // This event is sent by the switch to remove disconnected and errored peers.
  257. fsm.pool.RemovePeer(data.peerID, data.err)
  258. if fsm.pool.NumPeers() == 0 {
  259. return waitForPeer, nil
  260. }
  261. if fsm.pool.ReachedMaxHeight() {
  262. return finished, nil
  263. }
  264. return waitForBlock, nil
  265. case makeRequestsEv:
  266. fsm.makeNextRequests(data.maxNumRequests)
  267. return waitForBlock, nil
  268. case stateTimeoutEv:
  269. if data.stateName != "waitForBlock" {
  270. fsm.logger.Error("received a state timeout event for different state",
  271. "state", data.stateName)
  272. return waitForBlock, errTimeoutEventWrongState
  273. }
  274. // We haven't received the block at current height or height+1. Remove peer.
  275. fsm.pool.RemovePeerAtCurrentHeights(errNoPeerResponseForCurrentHeights)
  276. fsm.resetStateTimer()
  277. if fsm.pool.NumPeers() == 0 {
  278. return waitForPeer, errNoPeerResponseForCurrentHeights
  279. }
  280. if fsm.pool.ReachedMaxHeight() {
  281. return finished, nil
  282. }
  283. return waitForBlock, errNoPeerResponseForCurrentHeights
  284. case stopFSMEv:
  285. if fsm.stateTimer != nil {
  286. fsm.stateTimer.Stop()
  287. }
  288. return finished, errNoErrorFinished
  289. default:
  290. return waitForBlock, errInvalidEvent
  291. }
  292. },
  293. }
  294. finished = &bcReactorFSMState{
  295. name: "finished",
  296. enter: func(fsm *BcReactorFSM) {
  297. fsm.logger.Info("Time to switch to consensus reactor!", "height", fsm.pool.Height)
  298. fsm.toBcR.switchToConsensus()
  299. fsm.cleanup()
  300. },
  301. handle: func(fsm *BcReactorFSM, ev bReactorEvent, data bReactorEventData) (*bcReactorFSMState, error) {
  302. return finished, nil
  303. },
  304. }
  305. }
  306. // Interface used by FSM for sending Block and Status requests,
  307. // informing of peer errors and state timeouts
  308. // Implemented by BlockchainReactor and tests
  309. type bcReactor interface {
  310. sendStatusRequest()
  311. sendBlockRequest(peerID p2p.ID, height int64) error
  312. sendPeerError(err error, peerID p2p.ID)
  313. resetStateTimer(name string, timer **time.Timer, timeout time.Duration)
  314. switchToConsensus()
  315. }
  316. // SetLogger sets the FSM logger.
  317. func (fsm *BcReactorFSM) SetLogger(l log.Logger) {
  318. fsm.logger = l
  319. fsm.pool.SetLogger(l)
  320. }
  321. // Start starts the FSM.
  322. func (fsm *BcReactorFSM) Start() {
  323. _ = fsm.Handle(&bcReactorMessage{event: startFSMEv})
  324. }
  325. // Handle processes messages and events sent to the FSM.
  326. func (fsm *BcReactorFSM) Handle(msg *bcReactorMessage) error {
  327. fsm.mtx.Lock()
  328. defer fsm.mtx.Unlock()
  329. fsm.logger.Debug("FSM received", "event", msg, "state", fsm.state)
  330. if fsm.state == nil {
  331. fsm.state = unknown
  332. }
  333. next, err := fsm.state.handle(fsm, msg.event, msg.data)
  334. if err != nil {
  335. fsm.logger.Error("FSM event handler returned", "err", err,
  336. "state", fsm.state, "event", msg.event)
  337. }
  338. oldState := fsm.state.name
  339. fsm.transition(next)
  340. if oldState != fsm.state.name {
  341. fsm.logger.Info("FSM changed state", "new_state", fsm.state)
  342. }
  343. return err
  344. }
  345. func (fsm *BcReactorFSM) transition(next *bcReactorFSMState) {
  346. if next == nil {
  347. return
  348. }
  349. if fsm.state != next {
  350. fsm.state = next
  351. if next.enter != nil {
  352. next.enter(fsm)
  353. }
  354. }
  355. }
  356. // Called when entering an FSM state in order to detect lack of progress in the state machine.
  357. // Note the use of the 'bcr' interface to facilitate testing without timer expiring.
  358. func (fsm *BcReactorFSM) resetStateTimer() {
  359. fsm.toBcR.resetStateTimer(fsm.state.name, &fsm.stateTimer, fsm.state.timeout)
  360. }
  361. func (fsm *BcReactorFSM) isCaughtUp() bool {
  362. return fsm.state == finished
  363. }
  364. func (fsm *BcReactorFSM) makeNextRequests(maxNumRequests int) {
  365. fsm.pool.MakeNextRequests(maxNumRequests)
  366. }
  367. func (fsm *BcReactorFSM) cleanup() {
  368. fsm.pool.Cleanup()
  369. }
  370. // NeedsBlocks checks if more block requests are required.
  371. func (fsm *BcReactorFSM) NeedsBlocks() bool {
  372. fsm.mtx.Lock()
  373. defer fsm.mtx.Unlock()
  374. return fsm.state.name == "waitForBlock" && fsm.pool.NeedsBlocks()
  375. }
  376. // FirstTwoBlocks returns the two blocks at pool height and height+1
  377. func (fsm *BcReactorFSM) FirstTwoBlocks() (first, second *types.Block, err error) {
  378. fsm.mtx.Lock()
  379. defer fsm.mtx.Unlock()
  380. firstBP, secondBP, err := fsm.pool.FirstTwoBlocksAndPeers()
  381. if err == nil {
  382. first = firstBP.block
  383. second = secondBP.block
  384. }
  385. return
  386. }
  387. // Status returns the pool's height and the maximum peer height.
  388. func (fsm *BcReactorFSM) Status() (height, maxPeerHeight int64) {
  389. fsm.mtx.Lock()
  390. defer fsm.mtx.Unlock()
  391. return fsm.pool.Height, fsm.pool.MaxPeerHeight
  392. }