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.

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