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.

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