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.

391 lines
12 KiB

  1. # ADR 043: Blockhchain Reactor Riri-Org
  2. ## Changelog
  3. * 18-06-2019: Initial draft
  4. * 08-07-2019: Reviewed
  5. ## Context
  6. The blockchain reactor is responsible for two high level processes:sending/receiving blocks from peers and FastSync-ing blocks to catch upnode who is far behind. The goal of [ADR-40](https://github.com/tendermint/tendermint/blob/master/docs/architecture/adr-040-blockchain-reactor-refactor.md) was to refactor these two processes by separating business logic currently wrapped up in go-channels into pure `handle*` functions. While the ADR specified what the final form of the reactor might look like it lacked guidance on intermediary steps to get there.
  7. The following diagram illustrates the state of the [blockchain-reorg](https://github.com/tendermint/tendermint/pull/35610) reactor which will be referred to as `v1`.
  8. ![v1 Blockchain Reactor Architecture
  9. Diagram](https://github.com/tendermint/tendermint/blob/f9e556481654a24aeb689bdadaf5eab3ccd66829/docs/architecture/img/blockchain-reactor-v1.png)
  10. While `v1` of the blockchain reactor has shown significant improvements in terms of simplifying the concurrency model, the current PR has run into few roadblocks.
  11. * The current PR large and difficult to review.
  12. * Block gossiping and fast sync processes are highly coupled to the shared `Pool` data structure.
  13. * Peer communication is spread over multiple components creating complex dependency graph which must be mocked out during testing.
  14. * Timeouts modeled as stateful tickers introduce non-determinism in tests
  15. This ADR is meant to specify the missing components and control necessary to achieve [ADR-40](https://github.com/tendermint/tendermint/blob/master/docs/architecture/adr-040-blockchain-reactor-refactor.md).
  16. ## Decision
  17. Partition the responsibilities of the blockchain reactor into a set of components which communicate exclusively with events. Events will contain timestamps allowing each component to track time as internal state. The internal state will be mutated by a set of `handle*` which will produce event(s). The integration between components will happen in the reactor and reactor tests will then become integration tests between components. This design will be known as `v2`.
  18. ![v2 Blockchain Reactor Architecture
  19. Diagram](https://github.com/tendermint/tendermint/blob/f9e556481654a24aeb689bdadaf5eab3ccd66829/docs/architecture/img/blockchain-reactor-v2.png)
  20. ### Reactor changes in detail
  21. The reactor will include a demultiplexing routine which will send each message to each sub routine for independent processing. Each sub routine will then select the messages it's interested in and call the handle specific function specified in [ADR-40](https://github.com/tendermint/tendermint/blob/master/docs/architecture/adr-040-blockchain-reactor-refactor.md). The demuxRoutine acts as "pacemaker" setting the time in which events are expected to be handled.
  22. ```go
  23. func demuxRoutine(msgs, scheduleMsgs, processorMsgs, ioMsgs) {
  24. timer := time.NewTicker(interval)
  25. for {
  26. select {
  27. case <-timer.C:
  28. now := evTimeCheck{time.Now()}
  29. schedulerMsgs <- now
  30. processorMsgs <- now
  31. ioMsgs <- now
  32. case msg:= <- msgs:
  33. msg.time = time.Now()
  34. // These channels should produce backpressure before
  35. // being full to avoid starving each other
  36. schedulerMsgs <- msg
  37. processorMsgs <- msg
  38. ioMesgs <- msg
  39. if msg == stop {
  40. break;
  41. }
  42. }
  43. }
  44. }
  45. func processRoutine(input chan Message, output chan Message) {
  46. processor := NewProcessor(..)
  47. for {
  48. msg := <- input
  49. switch msg := msg.(type) {
  50. case bcBlockRequestMessage:
  51. output <- processor.handleBlockRequest(msg))
  52. ...
  53. case stop:
  54. processor.stop()
  55. break;
  56. }
  57. }
  58. func scheduleRoutine(input chan Message, output chan Message) {
  59. schelduer = NewScheduler(...)
  60. for {
  61. msg := <-msgs
  62. switch msg := input.(type) {
  63. case bcBlockResponseMessage:
  64. output <- scheduler.handleBlockResponse(msg)
  65. ...
  66. case stop:
  67. schedule.stop()
  68. break;
  69. }
  70. }
  71. }
  72. ```
  73. ## Lifecycle management
  74. A set of routines for individual processes allow processes to run in parallel with clear lifecycle management. `Start`, `Stop`, and `AddPeer` hooks currently present in the reactor will delegate to the sub-routines allowing them to manage internal state independent without further coupling to the reactor.
  75. ```go
  76. func (r *BlockChainReactor) Start() {
  77. r.msgs := make(chan Message, maxInFlight)
  78. schedulerMsgs := make(chan Message)
  79. processorMsgs := make(chan Message)
  80. ioMsgs := make(chan Message)
  81. go processorRoutine(processorMsgs, r.msgs)
  82. go scheduleRoutine(schedulerMsgs, r.msgs)
  83. go ioRoutine(ioMsgs, r.msgs)
  84. ...
  85. }
  86. func (bcR *BlockchainReactor) Receive(...) {
  87. ...
  88. r.msgs <- msg
  89. ...
  90. }
  91. func (r *BlockchainReactor) Stop() {
  92. ...
  93. r.msgs <- stop
  94. ...
  95. }
  96. ...
  97. func (r *BlockchainReactor) Stop() {
  98. ...
  99. r.msgs <- stop
  100. ...
  101. }
  102. ...
  103. func (r *BlockchainReactor) AddPeer(peer p2p.Peer) {
  104. ...
  105. r.msgs <- bcAddPeerEv{peer.ID}
  106. ...
  107. }
  108. ```
  109. ## IO handling
  110. An io handling routine within the reactor will isolate peer communication. Message going through the ioRoutine will usually be one way, using `p2p` APIs. In the case in which the `p2p` API such as `trySend` return errors, the ioRoutine can funnel those message back to the demuxRoutine for distribution to the other routines. For instance errors from the ioRoutine can be consumed by the scheduler to inform better peer selection implementations.
  111. ```go
  112. func (r *BlockchainReacor) ioRoutine(ioMesgs chan Message, outMsgs chan Message) {
  113. ...
  114. for {
  115. msg := <-ioMsgs
  116. switch msg := msg.(type) {
  117. case scBlockRequestMessage:
  118. queued := r.sendBlockRequestToPeer(...)
  119. if queued {
  120. outMsgs <- ioSendQueued{...}
  121. }
  122. case scStatusRequestMessage
  123. r.sendStatusRequestToPeer(...)
  124. case bcPeerError
  125. r.Swtich.StopPeerForError(msg.src)
  126. ...
  127. ...
  128. case bcFinished
  129. break;
  130. }
  131. }
  132. }
  133. ```
  134. ### Processor Internals
  135. The processor is responsible for ordering, verifying and executing blocks. The Processor will maintain an internal cursor `height` refering to the last processed block. As a set of blocks arrive unordered, the Processor will check if it has `height+1` necessary to process the next block. The processor also maintains the map `blockPeers` of peers to height, to keep track of which peer provided the block at `height`. `blockPeers` can be used in`handleRemovePeer(...)` to reschedule all unprocessed blocks provided by a peer who has errored.
  136. ```go
  137. type Processor struct {
  138. height int64 // the height cursor
  139. state ...
  140. blocks [height]*Block // keep a set of blocks in memory until they are processed
  141. blockPeers [height]PeerID // keep track of which heights came from which peerID
  142. lastTouch timestamp
  143. }
  144. func (proc *Processor) handleBlockResponse(peerID, block) {
  145. if block.height <= height || block[block.height] {
  146. } else if blocks[block.height] {
  147. return errDuplicateBlock{}
  148. } else {
  149. blocks[block.height] = block
  150. }
  151. if blocks[height] && blocks[height+1] {
  152. ... = state.Validators.VerifyCommit(...)
  153. ... = store.SaveBlock(...)
  154. state, err = blockExec.ApplyBlock(...)
  155. ...
  156. if err == nil {
  157. delete blocks[height]
  158. height++
  159. lastTouch = msg.time
  160. return pcBlockProcessed{height-1}
  161. } else {
  162. ... // Delete all unprocessed block from the peer
  163. return pcBlockProcessError{peerID, height}
  164. }
  165. }
  166. }
  167. func (proc *Processor) handleRemovePeer(peerID) {
  168. events = []
  169. // Delete all unprocessed blocks from peerID
  170. for i = height; i < len(blocks); i++ {
  171. if blockPeers[i] == peerID {
  172. events = append(events, pcBlockReschedule{height})
  173. delete block[height]
  174. }
  175. }
  176. return events
  177. }
  178. func handleTimeCheckEv(time) {
  179. if time - lastTouch > timeout {
  180. // Timeout the processor
  181. ...
  182. }
  183. }
  184. ```
  185. ## Schedule
  186. The Schedule maintains the internal state used for scheduling blockRequestMessages based on some scheduling algorithm. The schedule needs to maintain state on:
  187. * The state `blockState` of every block seem up to height of maxHeight
  188. * The set of peers and their peer state `peerState`
  189. * which peers have which blocks
  190. * which blocks have been requested from which peers
  191. ```go
  192. type blockState int
  193. const (
  194. blockStateNew = iota
  195. blockStatePending,
  196. blockStateReceived,
  197. blockStateProcessed
  198. )
  199. type schedule {
  200. // a list of blocks in which blockState
  201. blockStates map[height]blockState
  202. // a map of which blocks are available from which peers
  203. blockPeers map[height]map[p2p.ID]scPeer
  204. // a map of peerID to schedule specific peer struct `scPeer`
  205. peers map[p2p.ID]scPeer
  206. // a map of heights to the peer we are waiting for a response from
  207. pending map[height]scPeer
  208. targetPending int // the number of blocks we want in blockStatePending
  209. targetReceived int // the number of blocks we want in blockStateReceived
  210. peerTimeout int
  211. peerMinSpeed int
  212. }
  213. func (sc *schedule) numBlockInState(state blockState) uint32 {
  214. num := 0
  215. for i := sc.minHeight(); i <= sc.maxHeight(); i++ {
  216. if sc.blockState[i] == state {
  217. num++
  218. }
  219. }
  220. return num
  221. }
  222. func (sc *schedule) popSchedule(maxRequest int) []scBlockRequestMessage {
  223. // We only want to schedule requests such that we have less than sc.targetPending and sc.targetReceived
  224. // This ensures we don't saturate the network or flood the processor with unprocessed blocks
  225. todo := min(sc.targetPending - sc.numBlockInState(blockStatePending), sc.numBlockInState(blockStateReceived))
  226. events := []scBlockRequestMessage{}
  227. for i := sc.minHeight(); i < sc.maxMaxHeight(); i++ {
  228. if todo == 0 {
  229. break
  230. }
  231. if blockStates[i] == blockStateNew {
  232. peer = sc.selectPeer(blockPeers[i])
  233. sc.blockStates[i] = blockStatePending
  234. sc.pending[i] = peer
  235. events = append(events, scBlockRequestMessage{peerID: peer.peerID, height: i})
  236. todo--
  237. }
  238. }
  239. return events
  240. }
  241. ...
  242. type scPeer struct {
  243. peerID p2p.ID
  244. numOustandingRequest int
  245. lastTouched time.Time
  246. monitor flow.Monitor
  247. }
  248. ```
  249. # Scheduler
  250. The scheduler is configured to maintain a target `n` of in flight
  251. messages and will use feedback from `_blockResponseMessage`,
  252. `_statusResponseMessage` and `_peerError` produce an optimal assignment
  253. of scBlockRequestMessage at each `timeCheckEv`.
  254. ```
  255. func handleStatusResponse(peerID, height, time) {
  256. schedule.touchPeer(peerID, time)
  257. schedule.setPeerHeight(peerID, height)
  258. }
  259. func handleBlockResponseMessage(peerID, height, block, time) {
  260. schedule.touchPeer(peerID, time)
  261. schedule.markReceived(peerID, height, size(block))
  262. }
  263. func handleNoBlockResponseMessage(peerID, height, time) {
  264. schedule.touchPeer(peerID, time)
  265. // reschedule that block, punish peer...
  266. ...
  267. }
  268. func handlePeerError(peerID) {
  269. // Remove the peer, reschedule the requests
  270. ...
  271. }
  272. func handleTimeCheckEv(time) {
  273. // clean peer list
  274. events = []
  275. for peerID := range schedule.peersNotTouchedSince(time) {
  276. pending = schedule.pendingFrom(peerID)
  277. schedule.setPeerState(peerID, timedout)
  278. schedule.resetBlocks(pending)
  279. events = append(events, peerTimeout{peerID})
  280. }
  281. events = append(events, schedule.popSchedule())
  282. return events
  283. }
  284. ```
  285. ## Peer
  286. The Peer Stores per peer state based on messages received by the scheduler.
  287. ```go
  288. type Peer struct {
  289. lastTouched timestamp
  290. lastDownloaded timestamp
  291. pending map[height]struct{}
  292. height height // max height for the peer
  293. state {
  294. pending, // we know the peer but not the height
  295. active, // we know the height
  296. timeout // the peer has timed out
  297. }
  298. }
  299. ```
  300. ## Status
  301. Work in progress
  302. ## Consequences
  303. ### Positive
  304. * Test become deterministic
  305. * Simulation becomes a-termporal: no need wait for a wall-time timeout
  306. * Peer Selection can be independently tested/simulated
  307. * Develop a general approach to refactoring reactors
  308. ### Negative
  309. ### Neutral
  310. ### Implementation Path
  311. * Implement the scheduler, test the scheduler, review the rescheduler
  312. * Implement the processor, test the processor, review the processor
  313. * Implement the demuxer, write integration test, review integration tests
  314. ## References
  315. * [ADR-40](https://github.com/tendermint/tendermint/blob/master/docs/architecture/adr-040-blockchain-reactor-refactor.md): The original blockchain reactor re-org proposal
  316. * [Blockchain re-org](https://github.com/tendermint/tendermint/pull/3561): The current blockchain reactor re-org implementation (v1)