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.

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