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.

672 lines
18 KiB

cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
blocksync: fix shutdown deadlock issue (#7030) When shutting down blocksync, it is observed that the process can hang completely. A dump of running goroutines reveals that this is due to goroutines not listening on the correct shutdown signal. Namely, the `poolRoutine` goroutine does not wait on `pool.Quit`. The `poolRoutine` does not receive any other shutdown signal during `OnStop` becuase it must stop before the `r.closeCh` is closed. Currently the `poolRoutine` listens in the `closeCh` which will not close until the `poolRoutine` stops and calls `poolWG.Done()`. This change also puts the `requestRoutine()` in the `OnStart` method to make it more visible since it does not rely on anything that is spawned in the `poolRoutine`. ``` goroutine 183 [semacquire]: sync.runtime_Semacquire(0xc0000d3bd8) runtime/sema.go:56 +0x45 sync.(*WaitGroup).Wait(0xc0000d3bd0) sync/waitgroup.go:130 +0x65 github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStop(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:193 +0x47 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc0000d3a00, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/node.(*nodeImpl).OnStop(0xc00052c000) github.com/tendermint/tendermint/node/node.go:758 +0xc62 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc00052c000, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/cmd/tendermint/commands.NewRunNodeCmd.func1.1() github.com/tendermint/tendermint/cmd/tendermint/commands/run_node.go:143 +0x62 github.com/tendermint/tendermint/libs/os.TrapSignal.func1(0xc000df6d20, 0x7f04a68da900, 0xc0004a8930, 0xc0005a72d8) github.com/tendermint/tendermint/libs/os/os.go:26 +0x102 created by github.com/tendermint/tendermint/libs/os.TrapSignal github.com/tendermint/tendermint/libs/os/os.go:22 +0xe6 goroutine 161 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).poolRoutine(0xc0000d3a00, 0x0) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:464 +0x2b3 created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:174 +0xf1 goroutine 162 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).processBlockSyncCh(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:310 +0x151 created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:177 +0x54 goroutine 163 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).processPeerUpdates(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:363 +0x12b created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:178 +0x76 ```
3 years ago
blocksync: fix shutdown deadlock issue (#7030) When shutting down blocksync, it is observed that the process can hang completely. A dump of running goroutines reveals that this is due to goroutines not listening on the correct shutdown signal. Namely, the `poolRoutine` goroutine does not wait on `pool.Quit`. The `poolRoutine` does not receive any other shutdown signal during `OnStop` becuase it must stop before the `r.closeCh` is closed. Currently the `poolRoutine` listens in the `closeCh` which will not close until the `poolRoutine` stops and calls `poolWG.Done()`. This change also puts the `requestRoutine()` in the `OnStart` method to make it more visible since it does not rely on anything that is spawned in the `poolRoutine`. ``` goroutine 183 [semacquire]: sync.runtime_Semacquire(0xc0000d3bd8) runtime/sema.go:56 +0x45 sync.(*WaitGroup).Wait(0xc0000d3bd0) sync/waitgroup.go:130 +0x65 github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStop(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:193 +0x47 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc0000d3a00, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/node.(*nodeImpl).OnStop(0xc00052c000) github.com/tendermint/tendermint/node/node.go:758 +0xc62 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc00052c000, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/cmd/tendermint/commands.NewRunNodeCmd.func1.1() github.com/tendermint/tendermint/cmd/tendermint/commands/run_node.go:143 +0x62 github.com/tendermint/tendermint/libs/os.TrapSignal.func1(0xc000df6d20, 0x7f04a68da900, 0xc0004a8930, 0xc0005a72d8) github.com/tendermint/tendermint/libs/os/os.go:26 +0x102 created by github.com/tendermint/tendermint/libs/os.TrapSignal github.com/tendermint/tendermint/libs/os/os.go:22 +0xe6 goroutine 161 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).poolRoutine(0xc0000d3a00, 0x0) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:464 +0x2b3 created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:174 +0xf1 goroutine 162 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).processBlockSyncCh(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:310 +0x151 created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:177 +0x54 goroutine 163 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).processPeerUpdates(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:363 +0x12b created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:178 +0x76 ```
3 years ago
blocksync: fix shutdown deadlock issue (#7030) When shutting down blocksync, it is observed that the process can hang completely. A dump of running goroutines reveals that this is due to goroutines not listening on the correct shutdown signal. Namely, the `poolRoutine` goroutine does not wait on `pool.Quit`. The `poolRoutine` does not receive any other shutdown signal during `OnStop` becuase it must stop before the `r.closeCh` is closed. Currently the `poolRoutine` listens in the `closeCh` which will not close until the `poolRoutine` stops and calls `poolWG.Done()`. This change also puts the `requestRoutine()` in the `OnStart` method to make it more visible since it does not rely on anything that is spawned in the `poolRoutine`. ``` goroutine 183 [semacquire]: sync.runtime_Semacquire(0xc0000d3bd8) runtime/sema.go:56 +0x45 sync.(*WaitGroup).Wait(0xc0000d3bd0) sync/waitgroup.go:130 +0x65 github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStop(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:193 +0x47 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc0000d3a00, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/node.(*nodeImpl).OnStop(0xc00052c000) github.com/tendermint/tendermint/node/node.go:758 +0xc62 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc00052c000, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/cmd/tendermint/commands.NewRunNodeCmd.func1.1() github.com/tendermint/tendermint/cmd/tendermint/commands/run_node.go:143 +0x62 github.com/tendermint/tendermint/libs/os.TrapSignal.func1(0xc000df6d20, 0x7f04a68da900, 0xc0004a8930, 0xc0005a72d8) github.com/tendermint/tendermint/libs/os/os.go:26 +0x102 created by github.com/tendermint/tendermint/libs/os.TrapSignal github.com/tendermint/tendermint/libs/os/os.go:22 +0xe6 goroutine 161 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).poolRoutine(0xc0000d3a00, 0x0) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:464 +0x2b3 created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:174 +0xf1 goroutine 162 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).processBlockSyncCh(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:310 +0x151 created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:177 +0x54 goroutine 163 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).processPeerUpdates(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:363 +0x12b created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:178 +0x76 ```
3 years ago
blocksync: fix shutdown deadlock issue (#7030) When shutting down blocksync, it is observed that the process can hang completely. A dump of running goroutines reveals that this is due to goroutines not listening on the correct shutdown signal. Namely, the `poolRoutine` goroutine does not wait on `pool.Quit`. The `poolRoutine` does not receive any other shutdown signal during `OnStop` becuase it must stop before the `r.closeCh` is closed. Currently the `poolRoutine` listens in the `closeCh` which will not close until the `poolRoutine` stops and calls `poolWG.Done()`. This change also puts the `requestRoutine()` in the `OnStart` method to make it more visible since it does not rely on anything that is spawned in the `poolRoutine`. ``` goroutine 183 [semacquire]: sync.runtime_Semacquire(0xc0000d3bd8) runtime/sema.go:56 +0x45 sync.(*WaitGroup).Wait(0xc0000d3bd0) sync/waitgroup.go:130 +0x65 github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStop(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:193 +0x47 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc0000d3a00, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/node.(*nodeImpl).OnStop(0xc00052c000) github.com/tendermint/tendermint/node/node.go:758 +0xc62 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc00052c000, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/cmd/tendermint/commands.NewRunNodeCmd.func1.1() github.com/tendermint/tendermint/cmd/tendermint/commands/run_node.go:143 +0x62 github.com/tendermint/tendermint/libs/os.TrapSignal.func1(0xc000df6d20, 0x7f04a68da900, 0xc0004a8930, 0xc0005a72d8) github.com/tendermint/tendermint/libs/os/os.go:26 +0x102 created by github.com/tendermint/tendermint/libs/os.TrapSignal github.com/tendermint/tendermint/libs/os/os.go:22 +0xe6 goroutine 161 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).poolRoutine(0xc0000d3a00, 0x0) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:464 +0x2b3 created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:174 +0xf1 goroutine 162 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).processBlockSyncCh(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:310 +0x151 created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:177 +0x54 goroutine 163 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).processPeerUpdates(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:363 +0x12b created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:178 +0x76 ```
3 years ago
  1. package blocksync
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "runtime/debug"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/tendermint/tendermint/internal/consensus"
  11. "github.com/tendermint/tendermint/internal/eventbus"
  12. "github.com/tendermint/tendermint/internal/p2p"
  13. sm "github.com/tendermint/tendermint/internal/state"
  14. "github.com/tendermint/tendermint/internal/store"
  15. "github.com/tendermint/tendermint/libs/log"
  16. "github.com/tendermint/tendermint/libs/service"
  17. bcproto "github.com/tendermint/tendermint/proto/tendermint/blocksync"
  18. "github.com/tendermint/tendermint/types"
  19. )
  20. var _ service.Service = (*Reactor)(nil)
  21. const (
  22. // BlockSyncChannel is a channel for blocks and status updates
  23. BlockSyncChannel = p2p.ChannelID(0x40)
  24. trySyncIntervalMS = 10
  25. // ask for best height every 10s
  26. statusUpdateIntervalSeconds = 10
  27. // check if we should switch to consensus reactor
  28. switchToConsensusIntervalSeconds = 1
  29. // switch to consensus after this duration of inactivity
  30. syncTimeout = 60 * time.Second
  31. )
  32. func GetChannelDescriptor() *p2p.ChannelDescriptor {
  33. return &p2p.ChannelDescriptor{
  34. ID: BlockSyncChannel,
  35. MessageType: new(bcproto.Message),
  36. Priority: 5,
  37. SendQueueCapacity: 1000,
  38. RecvBufferCapacity: 1024,
  39. RecvMessageCapacity: MaxMsgSize,
  40. }
  41. }
  42. type consensusReactor interface {
  43. // For when we switch from block sync reactor to the consensus
  44. // machine.
  45. SwitchToConsensus(ctx context.Context, state sm.State, skipWAL bool)
  46. }
  47. type peerError struct {
  48. err error
  49. peerID types.NodeID
  50. }
  51. func (e peerError) Error() string {
  52. return fmt.Sprintf("error with peer %v: %s", e.peerID, e.err.Error())
  53. }
  54. // Reactor handles long-term catchup syncing.
  55. type Reactor struct {
  56. service.BaseService
  57. logger log.Logger
  58. // immutable
  59. initialState sm.State
  60. blockExec *sm.BlockExecutor
  61. store *store.BlockStore
  62. pool *BlockPool
  63. consReactor consensusReactor
  64. blockSync *atomicBool
  65. blockSyncCh *p2p.Channel
  66. // blockSyncOutBridgeCh defines a channel that acts as a bridge between sending Envelope
  67. // messages that the reactor will consume in processBlockSyncCh and receiving messages
  68. // from the peer updates channel and other goroutines. We do this instead of directly
  69. // sending on blockSyncCh.Out to avoid race conditions in the case where other goroutines
  70. // send Envelopes directly to the to blockSyncCh.Out channel, since processBlockSyncCh
  71. // may close the blockSyncCh.Out channel at the same time that other goroutines send to
  72. // blockSyncCh.Out.
  73. blockSyncOutBridgeCh chan p2p.Envelope
  74. peerUpdates *p2p.PeerUpdates
  75. requestsCh <-chan BlockRequest
  76. errorsCh <-chan peerError
  77. // poolWG is used to synchronize the graceful shutdown of the poolRoutine and
  78. // requestRoutine spawned goroutines when stopping the reactor and before
  79. // stopping the p2p Channel(s).
  80. poolWG sync.WaitGroup
  81. metrics *consensus.Metrics
  82. eventBus *eventbus.EventBus
  83. syncStartTime time.Time
  84. }
  85. // NewReactor returns new reactor instance.
  86. func NewReactor(
  87. ctx context.Context,
  88. logger log.Logger,
  89. state sm.State,
  90. blockExec *sm.BlockExecutor,
  91. store *store.BlockStore,
  92. consReactor consensusReactor,
  93. channelCreator p2p.ChannelCreator,
  94. peerUpdates *p2p.PeerUpdates,
  95. blockSync bool,
  96. metrics *consensus.Metrics,
  97. eventBus *eventbus.EventBus,
  98. ) (*Reactor, error) {
  99. if state.LastBlockHeight != store.Height() {
  100. return nil, fmt.Errorf("state (%v) and store (%v) height mismatch", state.LastBlockHeight, store.Height())
  101. }
  102. startHeight := store.Height() + 1
  103. if startHeight == 1 {
  104. startHeight = state.InitialHeight
  105. }
  106. requestsCh := make(chan BlockRequest, maxTotalRequesters)
  107. errorsCh := make(chan peerError, maxPeerErrBuffer) // NOTE: The capacity should be larger than the peer count.
  108. blockSyncCh, err := channelCreator(ctx, GetChannelDescriptor())
  109. if err != nil {
  110. return nil, err
  111. }
  112. r := &Reactor{
  113. logger: logger,
  114. initialState: state,
  115. blockExec: blockExec,
  116. store: store,
  117. pool: NewBlockPool(logger, startHeight, requestsCh, errorsCh),
  118. consReactor: consReactor,
  119. blockSync: newAtomicBool(blockSync),
  120. requestsCh: requestsCh,
  121. errorsCh: errorsCh,
  122. blockSyncCh: blockSyncCh,
  123. blockSyncOutBridgeCh: make(chan p2p.Envelope),
  124. peerUpdates: peerUpdates,
  125. metrics: metrics,
  126. eventBus: eventBus,
  127. syncStartTime: time.Time{},
  128. }
  129. r.BaseService = *service.NewBaseService(logger, "BlockSync", r)
  130. return r, nil
  131. }
  132. // OnStart starts separate go routines for each p2p Channel and listens for
  133. // envelopes on each. In addition, it also listens for peer updates and handles
  134. // messages on that p2p channel accordingly. The caller must be sure to execute
  135. // OnStop to ensure the outbound p2p Channels are closed.
  136. //
  137. // If blockSync is enabled, we also start the pool and the pool processing
  138. // goroutine. If the pool fails to start, an error is returned.
  139. func (r *Reactor) OnStart(ctx context.Context) error {
  140. if r.blockSync.IsSet() {
  141. if err := r.pool.Start(ctx); err != nil {
  142. return err
  143. }
  144. r.poolWG.Add(1)
  145. go r.requestRoutine(ctx)
  146. r.poolWG.Add(1)
  147. go r.poolRoutine(ctx, false)
  148. }
  149. go r.processBlockSyncCh(ctx)
  150. go r.processBlockSyncBridge(ctx)
  151. go r.processPeerUpdates(ctx)
  152. return nil
  153. }
  154. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  155. // blocking until they all exit.
  156. func (r *Reactor) OnStop() {
  157. if r.blockSync.IsSet() {
  158. if err := r.pool.Stop(); err != nil {
  159. r.logger.Error("failed to stop pool", "err", err)
  160. }
  161. }
  162. // wait for the poolRoutine and requestRoutine goroutines to gracefully exit
  163. r.poolWG.Wait()
  164. }
  165. // respondToPeer loads a block and sends it to the requesting peer, if we have it.
  166. // Otherwise, we'll respond saying we do not have it.
  167. func (r *Reactor) respondToPeer(ctx context.Context, msg *bcproto.BlockRequest, peerID types.NodeID) error {
  168. block := r.store.LoadBlock(msg.Height)
  169. if block != nil {
  170. blockProto, err := block.ToProto()
  171. if err != nil {
  172. r.logger.Error("failed to convert msg to protobuf", "err", err)
  173. return err
  174. }
  175. return r.blockSyncCh.Send(ctx, p2p.Envelope{
  176. To: peerID,
  177. Message: &bcproto.BlockResponse{Block: blockProto},
  178. })
  179. }
  180. r.logger.Info("peer requesting a block we do not have", "peer", peerID, "height", msg.Height)
  181. return r.blockSyncCh.Send(ctx, p2p.Envelope{
  182. To: peerID,
  183. Message: &bcproto.NoBlockResponse{Height: msg.Height},
  184. })
  185. }
  186. // handleBlockSyncMessage handles envelopes sent from peers on the
  187. // BlockSyncChannel. It returns an error only if the Envelope.Message is unknown
  188. // for this channel. This should never be called outside of handleMessage.
  189. func (r *Reactor) handleBlockSyncMessage(ctx context.Context, envelope *p2p.Envelope) error {
  190. logger := r.logger.With("peer", envelope.From)
  191. switch msg := envelope.Message.(type) {
  192. case *bcproto.BlockRequest:
  193. return r.respondToPeer(ctx, msg, envelope.From)
  194. case *bcproto.BlockResponse:
  195. block, err := types.BlockFromProto(msg.Block)
  196. if err != nil {
  197. logger.Error("failed to convert block from proto", "err", err)
  198. return err
  199. }
  200. r.pool.AddBlock(envelope.From, block, block.Size())
  201. case *bcproto.StatusRequest:
  202. return r.blockSyncCh.Send(ctx, p2p.Envelope{
  203. To: envelope.From,
  204. Message: &bcproto.StatusResponse{
  205. Height: r.store.Height(),
  206. Base: r.store.Base(),
  207. },
  208. })
  209. case *bcproto.StatusResponse:
  210. r.pool.SetPeerRange(envelope.From, msg.Base, msg.Height)
  211. case *bcproto.NoBlockResponse:
  212. logger.Debug("peer does not have the requested block", "height", msg.Height)
  213. default:
  214. return fmt.Errorf("received unknown message: %T", msg)
  215. }
  216. return nil
  217. }
  218. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  219. // It will handle errors and any possible panics gracefully. A caller can handle
  220. // any error returned by sending a PeerError on the respective channel.
  221. func (r *Reactor) handleMessage(ctx context.Context, chID p2p.ChannelID, envelope *p2p.Envelope) (err error) {
  222. defer func() {
  223. if e := recover(); e != nil {
  224. err = fmt.Errorf("panic in processing message: %v", e)
  225. r.logger.Error(
  226. "recovering from processing message panic",
  227. "err", err,
  228. "stack", string(debug.Stack()),
  229. )
  230. }
  231. }()
  232. r.logger.Debug("received message", "message", envelope.Message, "peer", envelope.From)
  233. switch chID {
  234. case BlockSyncChannel:
  235. err = r.handleBlockSyncMessage(ctx, envelope)
  236. default:
  237. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  238. }
  239. return err
  240. }
  241. // processBlockSyncCh initiates a blocking process where we listen for and handle
  242. // envelopes on the BlockSyncChannel and blockSyncOutBridgeCh. Any error encountered during
  243. // message execution will result in a PeerError being sent on the BlockSyncChannel.
  244. // When the reactor is stopped, we will catch the signal and close the p2p Channel
  245. // gracefully.
  246. func (r *Reactor) processBlockSyncCh(ctx context.Context) {
  247. iter := r.blockSyncCh.Receive(ctx)
  248. for iter.Next(ctx) {
  249. envelope := iter.Envelope()
  250. if err := r.handleMessage(ctx, r.blockSyncCh.ID, envelope); err != nil {
  251. if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
  252. return
  253. }
  254. r.logger.Error("failed to process message", "ch_id", r.blockSyncCh.ID, "envelope", envelope, "err", err)
  255. if serr := r.blockSyncCh.SendError(ctx, p2p.PeerError{
  256. NodeID: envelope.From,
  257. Err: err,
  258. }); serr != nil {
  259. return
  260. }
  261. }
  262. }
  263. }
  264. func (r *Reactor) processBlockSyncBridge(ctx context.Context) {
  265. for {
  266. select {
  267. case <-ctx.Done():
  268. return
  269. case envelope := <-r.blockSyncOutBridgeCh:
  270. if err := r.blockSyncCh.Send(ctx, envelope); err != nil {
  271. return
  272. }
  273. }
  274. }
  275. }
  276. // processPeerUpdate processes a PeerUpdate.
  277. func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
  278. r.logger.Debug("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  279. // XXX: Pool#RedoRequest can sometimes give us an empty peer.
  280. if len(peerUpdate.NodeID) == 0 {
  281. return
  282. }
  283. switch peerUpdate.Status {
  284. case p2p.PeerStatusUp:
  285. // send a status update the newly added peer
  286. r.blockSyncOutBridgeCh <- p2p.Envelope{
  287. To: peerUpdate.NodeID,
  288. Message: &bcproto.StatusResponse{
  289. Base: r.store.Base(),
  290. Height: r.store.Height(),
  291. },
  292. }
  293. case p2p.PeerStatusDown:
  294. r.pool.RemovePeer(peerUpdate.NodeID)
  295. }
  296. }
  297. // processPeerUpdates initiates a blocking process where we listen for and handle
  298. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  299. // close the p2p PeerUpdatesCh gracefully.
  300. func (r *Reactor) processPeerUpdates(ctx context.Context) {
  301. for {
  302. select {
  303. case <-ctx.Done():
  304. return
  305. case peerUpdate := <-r.peerUpdates.Updates():
  306. r.processPeerUpdate(peerUpdate)
  307. }
  308. }
  309. }
  310. // SwitchToBlockSync is called by the state sync reactor when switching to fast
  311. // sync.
  312. func (r *Reactor) SwitchToBlockSync(ctx context.Context, state sm.State) error {
  313. r.blockSync.Set()
  314. r.initialState = state
  315. r.pool.height = state.LastBlockHeight + 1
  316. if err := r.pool.Start(ctx); err != nil {
  317. return err
  318. }
  319. r.syncStartTime = time.Now()
  320. r.poolWG.Add(1)
  321. go r.requestRoutine(ctx)
  322. r.poolWG.Add(1)
  323. go r.poolRoutine(ctx, true)
  324. return nil
  325. }
  326. func (r *Reactor) requestRoutine(ctx context.Context) {
  327. statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second)
  328. defer statusUpdateTicker.Stop()
  329. defer r.poolWG.Done()
  330. for {
  331. select {
  332. case <-ctx.Done():
  333. return
  334. case request := <-r.requestsCh:
  335. r.blockSyncOutBridgeCh <- p2p.Envelope{
  336. To: request.PeerID,
  337. Message: &bcproto.BlockRequest{Height: request.Height},
  338. }
  339. case pErr := <-r.errorsCh:
  340. if err := r.blockSyncCh.SendError(ctx, p2p.PeerError{
  341. NodeID: pErr.peerID,
  342. Err: pErr.err,
  343. }); err != nil {
  344. return
  345. }
  346. case <-statusUpdateTicker.C:
  347. r.poolWG.Add(1)
  348. go func() {
  349. defer r.poolWG.Done()
  350. select {
  351. case r.blockSyncOutBridgeCh <- p2p.Envelope{
  352. Broadcast: true,
  353. Message: &bcproto.StatusRequest{},
  354. }:
  355. case <-ctx.Done():
  356. }
  357. }()
  358. }
  359. }
  360. }
  361. // poolRoutine handles messages from the poolReactor telling the reactor what to
  362. // do.
  363. //
  364. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down!
  365. func (r *Reactor) poolRoutine(ctx context.Context, stateSynced bool) {
  366. var (
  367. trySyncTicker = time.NewTicker(trySyncIntervalMS * time.Millisecond)
  368. switchToConsensusTicker = time.NewTicker(switchToConsensusIntervalSeconds * time.Second)
  369. blocksSynced = uint64(0)
  370. chainID = r.initialState.ChainID
  371. state = r.initialState
  372. lastHundred = time.Now()
  373. lastRate = 0.0
  374. didProcessCh = make(chan struct{}, 1)
  375. )
  376. defer trySyncTicker.Stop()
  377. defer switchToConsensusTicker.Stop()
  378. defer r.poolWG.Done()
  379. FOR_LOOP:
  380. for {
  381. select {
  382. case <-switchToConsensusTicker.C:
  383. var (
  384. height, numPending, lenRequesters = r.pool.GetStatus()
  385. lastAdvance = r.pool.LastAdvance()
  386. )
  387. r.logger.Debug(
  388. "consensus ticker",
  389. "num_pending", numPending,
  390. "total", lenRequesters,
  391. "height", height,
  392. )
  393. switch {
  394. case r.pool.IsCaughtUp():
  395. r.logger.Info("switching to consensus reactor", "height", height)
  396. case time.Since(lastAdvance) > syncTimeout:
  397. r.logger.Error("no progress since last advance", "last_advance", lastAdvance)
  398. default:
  399. r.logger.Info(
  400. "not caught up yet",
  401. "height", height,
  402. "max_peer_height", r.pool.MaxPeerHeight(),
  403. "timeout_in", syncTimeout-time.Since(lastAdvance),
  404. )
  405. continue
  406. }
  407. if err := r.pool.Stop(); err != nil {
  408. r.logger.Error("failed to stop pool", "err", err)
  409. }
  410. r.blockSync.UnSet()
  411. if r.consReactor != nil {
  412. r.consReactor.SwitchToConsensus(ctx, state, blocksSynced > 0 || stateSynced)
  413. }
  414. break FOR_LOOP
  415. case <-trySyncTicker.C:
  416. select {
  417. case didProcessCh <- struct{}{}:
  418. default:
  419. }
  420. case <-didProcessCh:
  421. // NOTE: It is a subtle mistake to process more than a single block at a
  422. // time (e.g. 10) here, because we only send one BlockRequest per loop
  423. // iteration. The ratio mismatch can result in starving of blocks, i.e. a
  424. // sudden burst of requests and responses, and repeat. Consequently, it is
  425. // better to split these routines rather than coupling them as it is
  426. // written here.
  427. //
  428. // TODO: Uncouple from request routine.
  429. // see if there are any blocks to sync
  430. first, second := r.pool.PeekTwoBlocks()
  431. if first == nil || second == nil {
  432. // we need both to sync the first block
  433. continue FOR_LOOP
  434. } else {
  435. // try again quickly next loop
  436. didProcessCh <- struct{}{}
  437. }
  438. firstParts, err := first.MakePartSet(types.BlockPartSizeBytes)
  439. if err != nil {
  440. r.logger.Error("failed to make ",
  441. "height", first.Height,
  442. "err", err.Error())
  443. break FOR_LOOP
  444. }
  445. var (
  446. firstPartSetHeader = firstParts.Header()
  447. firstID = types.BlockID{Hash: first.Hash(), PartSetHeader: firstPartSetHeader}
  448. )
  449. // Finally, verify the first block using the second's commit.
  450. //
  451. // NOTE: We can probably make this more efficient, but note that calling
  452. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  453. // currently necessary.
  454. if err = state.Validators.VerifyCommitLight(chainID, firstID, first.Height, second.LastCommit); err != nil {
  455. err = fmt.Errorf("invalid last commit: %w", err)
  456. r.logger.Error(
  457. err.Error(),
  458. "last_commit", second.LastCommit,
  459. "block_id", firstID,
  460. "height", first.Height,
  461. )
  462. // NOTE: We've already removed the peer's request, but we still need
  463. // to clean up the rest.
  464. peerID := r.pool.RedoRequest(first.Height)
  465. if serr := r.blockSyncCh.SendError(ctx, p2p.PeerError{
  466. NodeID: peerID,
  467. Err: err,
  468. }); serr != nil {
  469. break FOR_LOOP
  470. }
  471. peerID2 := r.pool.RedoRequest(second.Height)
  472. if peerID2 != peerID {
  473. if serr := r.blockSyncCh.SendError(ctx, p2p.PeerError{
  474. NodeID: peerID2,
  475. Err: err,
  476. }); serr != nil {
  477. break FOR_LOOP
  478. }
  479. }
  480. continue FOR_LOOP
  481. } else {
  482. r.pool.PopRequest()
  483. // TODO: batch saves so we do not persist to disk every block
  484. r.store.SaveBlock(first, firstParts, second.LastCommit)
  485. var err error
  486. // TODO: Same thing for app - but we would need a way to get the hash
  487. // without persisting the state.
  488. state, err = r.blockExec.ApplyBlock(ctx, state, firstID, first)
  489. if err != nil {
  490. // TODO: This is bad, are we zombie?
  491. panic(fmt.Sprintf("failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  492. }
  493. r.metrics.RecordConsMetrics(first)
  494. blocksSynced++
  495. if blocksSynced%100 == 0 {
  496. lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds())
  497. r.logger.Info(
  498. "block sync rate",
  499. "height", r.pool.height,
  500. "max_peer_height", r.pool.MaxPeerHeight(),
  501. "blocks/s", lastRate,
  502. )
  503. lastHundred = time.Now()
  504. }
  505. }
  506. continue FOR_LOOP
  507. case <-ctx.Done():
  508. break FOR_LOOP
  509. case <-r.pool.exitedCh:
  510. break FOR_LOOP
  511. }
  512. }
  513. }
  514. func (r *Reactor) GetMaxPeerBlockHeight() int64 {
  515. return r.pool.MaxPeerHeight()
  516. }
  517. func (r *Reactor) GetTotalSyncedTime() time.Duration {
  518. if !r.blockSync.IsSet() || r.syncStartTime.IsZero() {
  519. return time.Duration(0)
  520. }
  521. return time.Since(r.syncStartTime)
  522. }
  523. func (r *Reactor) GetRemainingSyncTime() time.Duration {
  524. if !r.blockSync.IsSet() {
  525. return time.Duration(0)
  526. }
  527. targetSyncs := r.pool.targetSyncBlocks()
  528. currentSyncs := r.store.Height() - r.pool.startHeight + 1
  529. lastSyncRate := r.pool.getLastSyncRate()
  530. if currentSyncs < 0 || lastSyncRate < 0.001 {
  531. return time.Duration(0)
  532. }
  533. remain := float64(targetSyncs-currentSyncs) / lastSyncRate
  534. return time.Duration(int64(remain * float64(time.Second)))
  535. }
  536. func (r *Reactor) PublishStatus(ctx context.Context, event types.EventDataBlockSyncStatus) error {
  537. if r.eventBus == nil {
  538. return errors.New("event bus is not configured")
  539. }
  540. return r.eventBus.PublishEventBlockSyncStatus(ctx, event)
  541. }
  542. // atomicBool is an atomic Boolean, safe for concurrent use by multiple
  543. // goroutines.
  544. type atomicBool int32
  545. // newAtomicBool creates an atomicBool with given initial value.
  546. func newAtomicBool(ok bool) *atomicBool {
  547. ab := new(atomicBool)
  548. if ok {
  549. ab.Set()
  550. }
  551. return ab
  552. }
  553. // Set sets the Boolean to true.
  554. func (ab *atomicBool) Set() { atomic.StoreInt32((*int32)(ab), 1) }
  555. // UnSet sets the Boolean to false.
  556. func (ab *atomicBool) UnSet() { atomic.StoreInt32((*int32)(ab), 0) }
  557. // IsSet returns whether the Boolean is true.
  558. func (ab *atomicBool) IsSet() bool { return atomic.LoadInt32((*int32)(ab))&1 == 1 }