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.

1093 lines
31 KiB

statesync: remove deadlock on init fail (#7029) When statesync is stopped during shutdown, it has the possibility of deadlocking. A dump of goroutines reveals that this is related to the peerUpdates channel not returning anything on its `Done()` channel when `OnStop` is called. As this is occuring, `processPeerUpdate` is attempting to acquire the reactor lock. It appears that this lock can never be acquired. I looked for the places where the lock may remain locked accidentally and cleaned them up in hopes to eradicate the issue. Dumps of the relevant goroutines may be found below. Note that the line numbers below are relative to the code in the `v0.35.0-rc1` tag. ``` goroutine 36 [chan receive]: github.com/tendermint/tendermint/internal/statesync.(*Reactor).OnStop(0xc00058f200) github.com/tendermint/tendermint/internal/statesync/reactor.go:243 +0x117 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc00058f200, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/node.(*nodeImpl).OnStop(0xc0001ea240) github.com/tendermint/tendermint/node/node.go:769 +0x132 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc0001ea240, 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(0xc000629500, 0x7fdb52f96358, 0xc0002b5030, 0xc00000daa0) 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 188 [semacquire]: sync.runtime_SemacquireMutex(0xc00026b1cc, 0x0, 0x1) runtime/sema.go:71 +0x47 sync.(*Mutex).lockSlow(0xc00026b1c8) sync/mutex.go:138 +0x105 sync.(*Mutex).Lock(...) sync/mutex.go:81 sync.(*RWMutex).Lock(0xc00026b1c8) sync/rwmutex.go:111 +0x90 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdate(0xc00026b080, 0xc000650008, 0x28, 0x124de90, 0x4) github.com/tendermint/tendermint/internal/statesync/reactor.go:849 +0x1a5 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdates(0xc00026b080) github.com/tendermint/tendermint/internal/statesync/reactor.go:883 +0xab created by github.com/tendermint/tendermint/internal/statesync.(*Reactor.OnStart github.com/tendermint/tendermint/internal/statesync/reactor.go:219 +0xcd) ```
3 years ago
statesync: remove deadlock on init fail (#7029) When statesync is stopped during shutdown, it has the possibility of deadlocking. A dump of goroutines reveals that this is related to the peerUpdates channel not returning anything on its `Done()` channel when `OnStop` is called. As this is occuring, `processPeerUpdate` is attempting to acquire the reactor lock. It appears that this lock can never be acquired. I looked for the places where the lock may remain locked accidentally and cleaned them up in hopes to eradicate the issue. Dumps of the relevant goroutines may be found below. Note that the line numbers below are relative to the code in the `v0.35.0-rc1` tag. ``` goroutine 36 [chan receive]: github.com/tendermint/tendermint/internal/statesync.(*Reactor).OnStop(0xc00058f200) github.com/tendermint/tendermint/internal/statesync/reactor.go:243 +0x117 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc00058f200, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/node.(*nodeImpl).OnStop(0xc0001ea240) github.com/tendermint/tendermint/node/node.go:769 +0x132 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc0001ea240, 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(0xc000629500, 0x7fdb52f96358, 0xc0002b5030, 0xc00000daa0) 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 188 [semacquire]: sync.runtime_SemacquireMutex(0xc00026b1cc, 0x0, 0x1) runtime/sema.go:71 +0x47 sync.(*Mutex).lockSlow(0xc00026b1c8) sync/mutex.go:138 +0x105 sync.(*Mutex).Lock(...) sync/mutex.go:81 sync.(*RWMutex).Lock(0xc00026b1c8) sync/rwmutex.go:111 +0x90 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdate(0xc00026b080, 0xc000650008, 0x28, 0x124de90, 0x4) github.com/tendermint/tendermint/internal/statesync/reactor.go:849 +0x1a5 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdates(0xc00026b080) github.com/tendermint/tendermint/internal/statesync/reactor.go:883 +0xab created by github.com/tendermint/tendermint/internal/statesync.(*Reactor.OnStart github.com/tendermint/tendermint/internal/statesync/reactor.go:219 +0xcd) ```
3 years ago
statesync: remove deadlock on init fail (#7029) When statesync is stopped during shutdown, it has the possibility of deadlocking. A dump of goroutines reveals that this is related to the peerUpdates channel not returning anything on its `Done()` channel when `OnStop` is called. As this is occuring, `processPeerUpdate` is attempting to acquire the reactor lock. It appears that this lock can never be acquired. I looked for the places where the lock may remain locked accidentally and cleaned them up in hopes to eradicate the issue. Dumps of the relevant goroutines may be found below. Note that the line numbers below are relative to the code in the `v0.35.0-rc1` tag. ``` goroutine 36 [chan receive]: github.com/tendermint/tendermint/internal/statesync.(*Reactor).OnStop(0xc00058f200) github.com/tendermint/tendermint/internal/statesync/reactor.go:243 +0x117 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc00058f200, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/node.(*nodeImpl).OnStop(0xc0001ea240) github.com/tendermint/tendermint/node/node.go:769 +0x132 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc0001ea240, 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(0xc000629500, 0x7fdb52f96358, 0xc0002b5030, 0xc00000daa0) 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 188 [semacquire]: sync.runtime_SemacquireMutex(0xc00026b1cc, 0x0, 0x1) runtime/sema.go:71 +0x47 sync.(*Mutex).lockSlow(0xc00026b1c8) sync/mutex.go:138 +0x105 sync.(*Mutex).Lock(...) sync/mutex.go:81 sync.(*RWMutex).Lock(0xc00026b1c8) sync/rwmutex.go:111 +0x90 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdate(0xc00026b080, 0xc000650008, 0x28, 0x124de90, 0x4) github.com/tendermint/tendermint/internal/statesync/reactor.go:849 +0x1a5 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdates(0xc00026b080) github.com/tendermint/tendermint/internal/statesync/reactor.go:883 +0xab created by github.com/tendermint/tendermint/internal/statesync.(*Reactor.OnStart github.com/tendermint/tendermint/internal/statesync/reactor.go:219 +0xcd) ```
3 years ago
statesync: remove deadlock on init fail (#7029) When statesync is stopped during shutdown, it has the possibility of deadlocking. A dump of goroutines reveals that this is related to the peerUpdates channel not returning anything on its `Done()` channel when `OnStop` is called. As this is occuring, `processPeerUpdate` is attempting to acquire the reactor lock. It appears that this lock can never be acquired. I looked for the places where the lock may remain locked accidentally and cleaned them up in hopes to eradicate the issue. Dumps of the relevant goroutines may be found below. Note that the line numbers below are relative to the code in the `v0.35.0-rc1` tag. ``` goroutine 36 [chan receive]: github.com/tendermint/tendermint/internal/statesync.(*Reactor).OnStop(0xc00058f200) github.com/tendermint/tendermint/internal/statesync/reactor.go:243 +0x117 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc00058f200, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/node.(*nodeImpl).OnStop(0xc0001ea240) github.com/tendermint/tendermint/node/node.go:769 +0x132 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc0001ea240, 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(0xc000629500, 0x7fdb52f96358, 0xc0002b5030, 0xc00000daa0) 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 188 [semacquire]: sync.runtime_SemacquireMutex(0xc00026b1cc, 0x0, 0x1) runtime/sema.go:71 +0x47 sync.(*Mutex).lockSlow(0xc00026b1c8) sync/mutex.go:138 +0x105 sync.(*Mutex).Lock(...) sync/mutex.go:81 sync.(*RWMutex).Lock(0xc00026b1c8) sync/rwmutex.go:111 +0x90 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdate(0xc00026b080, 0xc000650008, 0x28, 0x124de90, 0x4) github.com/tendermint/tendermint/internal/statesync/reactor.go:849 +0x1a5 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdates(0xc00026b080) github.com/tendermint/tendermint/internal/statesync/reactor.go:883 +0xab created by github.com/tendermint/tendermint/internal/statesync.(*Reactor.OnStart github.com/tendermint/tendermint/internal/statesync/reactor.go:219 +0xcd) ```
3 years ago
  1. package statesync
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "reflect"
  8. "runtime/debug"
  9. "sort"
  10. "sync"
  11. "time"
  12. abci "github.com/tendermint/tendermint/abci/types"
  13. "github.com/tendermint/tendermint/config"
  14. "github.com/tendermint/tendermint/internal/p2p"
  15. "github.com/tendermint/tendermint/internal/proxy"
  16. sm "github.com/tendermint/tendermint/internal/state"
  17. "github.com/tendermint/tendermint/internal/store"
  18. "github.com/tendermint/tendermint/libs/log"
  19. "github.com/tendermint/tendermint/libs/service"
  20. "github.com/tendermint/tendermint/light"
  21. "github.com/tendermint/tendermint/light/provider"
  22. ssproto "github.com/tendermint/tendermint/proto/tendermint/statesync"
  23. "github.com/tendermint/tendermint/types"
  24. )
  25. var (
  26. _ service.Service = (*Reactor)(nil)
  27. _ p2p.Wrapper = (*ssproto.Message)(nil)
  28. )
  29. const (
  30. // SnapshotChannel exchanges snapshot metadata
  31. SnapshotChannel = p2p.ChannelID(0x60)
  32. // ChunkChannel exchanges chunk contents
  33. ChunkChannel = p2p.ChannelID(0x61)
  34. // LightBlockChannel exchanges light blocks
  35. LightBlockChannel = p2p.ChannelID(0x62)
  36. // ParamsChannel exchanges consensus params
  37. ParamsChannel = p2p.ChannelID(0x63)
  38. // recentSnapshots is the number of recent snapshots to send and receive per peer.
  39. recentSnapshots = 10
  40. // snapshotMsgSize is the maximum size of a snapshotResponseMessage
  41. snapshotMsgSize = int(4e6) // ~4MB
  42. // chunkMsgSize is the maximum size of a chunkResponseMessage
  43. chunkMsgSize = int(16e6) // ~16MB
  44. // lightBlockMsgSize is the maximum size of a lightBlockResponseMessage
  45. lightBlockMsgSize = int(1e7) // ~1MB
  46. // paramMsgSize is the maximum size of a paramsResponseMessage
  47. paramMsgSize = int(1e5) // ~100kb
  48. // lightBlockResponseTimeout is how long the dispatcher waits for a peer to
  49. // return a light block
  50. lightBlockResponseTimeout = 10 * time.Second
  51. // consensusParamsResponseTimeout is the time the p2p state provider waits
  52. // before performing a secondary call
  53. consensusParamsResponseTimeout = 5 * time.Second
  54. // maxLightBlockRequestRetries is the amount of retries acceptable before
  55. // the backfill process aborts
  56. maxLightBlockRequestRetries = 20
  57. )
  58. func getChannelDescriptors() map[p2p.ChannelID]*p2p.ChannelDescriptor {
  59. return map[p2p.ChannelID]*p2p.ChannelDescriptor{
  60. SnapshotChannel: {
  61. ID: SnapshotChannel,
  62. MessageType: new(ssproto.Message),
  63. Priority: 6,
  64. SendQueueCapacity: 10,
  65. RecvMessageCapacity: snapshotMsgSize,
  66. RecvBufferCapacity: 128,
  67. },
  68. ChunkChannel: {
  69. ID: ChunkChannel,
  70. Priority: 3,
  71. MessageType: new(ssproto.Message),
  72. SendQueueCapacity: 4,
  73. RecvMessageCapacity: chunkMsgSize,
  74. RecvBufferCapacity: 128,
  75. },
  76. LightBlockChannel: {
  77. ID: LightBlockChannel,
  78. MessageType: new(ssproto.Message),
  79. Priority: 5,
  80. SendQueueCapacity: 10,
  81. RecvMessageCapacity: lightBlockMsgSize,
  82. RecvBufferCapacity: 128,
  83. },
  84. ParamsChannel: {
  85. ID: ParamsChannel,
  86. MessageType: new(ssproto.Message),
  87. Priority: 2,
  88. SendQueueCapacity: 10,
  89. RecvMessageCapacity: paramMsgSize,
  90. RecvBufferCapacity: 128,
  91. },
  92. }
  93. }
  94. // Metricer defines an interface used for the rpc sync info query, please see statesync.metrics
  95. // for the details.
  96. type Metricer interface {
  97. TotalSnapshots() int64
  98. ChunkProcessAvgTime() time.Duration
  99. SnapshotHeight() int64
  100. SnapshotChunksCount() int64
  101. SnapshotChunksTotal() int64
  102. BackFilledBlocks() int64
  103. BackFillBlocksTotal() int64
  104. }
  105. // Reactor handles state sync, both restoring snapshots for the local node and
  106. // serving snapshots for other nodes.
  107. type Reactor struct {
  108. service.BaseService
  109. logger log.Logger
  110. chainID string
  111. initialHeight int64
  112. cfg config.StateSyncConfig
  113. stateStore sm.Store
  114. blockStore *store.BlockStore
  115. conn proxy.AppConnSnapshot
  116. connQuery proxy.AppConnQuery
  117. tempDir string
  118. snapshotCh *p2p.Channel
  119. chunkCh *p2p.Channel
  120. blockCh *p2p.Channel
  121. paramsCh *p2p.Channel
  122. peerUpdates *p2p.PeerUpdates
  123. // Dispatcher is used to multiplex light block requests and responses over multiple
  124. // peers used by the p2p state provider and in reverse sync.
  125. dispatcher *Dispatcher
  126. peers *peerList
  127. // These will only be set when a state sync is in progress. It is used to feed
  128. // received snapshots and chunks into the syncer and manage incoming and outgoing
  129. // providers.
  130. mtx sync.RWMutex
  131. syncer *syncer
  132. providers map[types.NodeID]*BlockProvider
  133. stateProvider StateProvider
  134. metrics *Metrics
  135. backfillBlockTotal int64
  136. backfilledBlocks int64
  137. }
  138. // NewReactor returns a reference to a new state sync reactor, which implements
  139. // the service.Service interface. It accepts a logger, connections for snapshots
  140. // and querying, references to p2p Channels and a channel to listen for peer
  141. // updates on. Note, the reactor will close all p2p Channels when stopping.
  142. func NewReactor(
  143. ctx context.Context,
  144. chainID string,
  145. initialHeight int64,
  146. cfg config.StateSyncConfig,
  147. logger log.Logger,
  148. conn proxy.AppConnSnapshot,
  149. connQuery proxy.AppConnQuery,
  150. channelCreator p2p.ChannelCreator,
  151. peerUpdates *p2p.PeerUpdates,
  152. stateStore sm.Store,
  153. blockStore *store.BlockStore,
  154. tempDir string,
  155. ssMetrics *Metrics,
  156. ) (*Reactor, error) {
  157. chDesc := getChannelDescriptors()
  158. snapshotCh, err := channelCreator(ctx, chDesc[SnapshotChannel])
  159. if err != nil {
  160. return nil, err
  161. }
  162. chunkCh, err := channelCreator(ctx, chDesc[ChunkChannel])
  163. if err != nil {
  164. return nil, err
  165. }
  166. blockCh, err := channelCreator(ctx, chDesc[LightBlockChannel])
  167. if err != nil {
  168. return nil, err
  169. }
  170. paramsCh, err := channelCreator(ctx, chDesc[ParamsChannel])
  171. if err != nil {
  172. return nil, err
  173. }
  174. r := &Reactor{
  175. logger: logger,
  176. chainID: chainID,
  177. initialHeight: initialHeight,
  178. cfg: cfg,
  179. conn: conn,
  180. connQuery: connQuery,
  181. snapshotCh: snapshotCh,
  182. chunkCh: chunkCh,
  183. blockCh: blockCh,
  184. paramsCh: paramsCh,
  185. peerUpdates: peerUpdates,
  186. tempDir: tempDir,
  187. stateStore: stateStore,
  188. blockStore: blockStore,
  189. peers: newPeerList(),
  190. dispatcher: NewDispatcher(blockCh),
  191. providers: make(map[types.NodeID]*BlockProvider),
  192. metrics: ssMetrics,
  193. }
  194. r.BaseService = *service.NewBaseService(logger, "StateSync", r)
  195. return r, nil
  196. }
  197. // OnStart starts separate go routines for each p2p Channel and listens for
  198. // envelopes on each. In addition, it also listens for peer updates and handles
  199. // messages on that p2p channel accordingly. Note, we do not launch a go-routine to
  200. // handle individual envelopes as to not have to deal with bounding workers or pools.
  201. // The caller must be sure to execute OnStop to ensure the outbound p2p Channels are
  202. // closed. No error is returned.
  203. func (r *Reactor) OnStart(ctx context.Context) error {
  204. go r.processCh(ctx, r.snapshotCh, "snapshot")
  205. go r.processCh(ctx, r.chunkCh, "chunk")
  206. go r.processCh(ctx, r.blockCh, "light block")
  207. go r.processCh(ctx, r.paramsCh, "consensus params")
  208. go r.processPeerUpdates(ctx)
  209. return nil
  210. }
  211. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  212. // blocking until they all exit.
  213. func (r *Reactor) OnStop() {
  214. // tell the dispatcher to stop sending any more requests
  215. r.dispatcher.Close()
  216. }
  217. // Sync runs a state sync, fetching snapshots and providing chunks to the
  218. // application. At the close of the operation, Sync will bootstrap the state
  219. // store and persist the commit at that height so that either consensus or
  220. // blocksync can commence. It will then proceed to backfill the necessary amount
  221. // of historical blocks before participating in consensus
  222. func (r *Reactor) Sync(ctx context.Context) (sm.State, error) {
  223. // We need at least two peers (for cross-referencing of light blocks) before we can
  224. // begin state sync
  225. if err := r.waitForEnoughPeers(ctx, 2); err != nil {
  226. return sm.State{}, err
  227. }
  228. r.mtx.Lock()
  229. if r.syncer != nil {
  230. r.mtx.Unlock()
  231. return sm.State{}, errors.New("a state sync is already in progress")
  232. }
  233. if err := r.initStateProvider(ctx, r.chainID, r.initialHeight); err != nil {
  234. r.mtx.Unlock()
  235. return sm.State{}, err
  236. }
  237. r.syncer = newSyncer(
  238. r.cfg,
  239. r.logger,
  240. r.conn,
  241. r.connQuery,
  242. r.stateProvider,
  243. r.snapshotCh,
  244. r.chunkCh,
  245. r.tempDir,
  246. r.metrics,
  247. )
  248. r.mtx.Unlock()
  249. defer func() {
  250. r.mtx.Lock()
  251. // reset syncing objects at the close of Sync
  252. r.syncer = nil
  253. r.stateProvider = nil
  254. r.mtx.Unlock()
  255. }()
  256. requestSnapshotsHook := func() error {
  257. // request snapshots from all currently connected peers
  258. return r.snapshotCh.Send(ctx, p2p.Envelope{
  259. Broadcast: true,
  260. Message: &ssproto.SnapshotsRequest{},
  261. })
  262. }
  263. state, commit, err := r.syncer.SyncAny(ctx, r.cfg.DiscoveryTime, requestSnapshotsHook)
  264. if err != nil {
  265. return sm.State{}, err
  266. }
  267. err = r.stateStore.Bootstrap(state)
  268. if err != nil {
  269. return sm.State{}, fmt.Errorf("failed to bootstrap node with new state: %w", err)
  270. }
  271. err = r.blockStore.SaveSeenCommit(state.LastBlockHeight, commit)
  272. if err != nil {
  273. return sm.State{}, fmt.Errorf("failed to store last seen commit: %w", err)
  274. }
  275. err = r.Backfill(ctx, state)
  276. if err != nil {
  277. r.logger.Error("backfill failed. Proceeding optimistically...", "err", err)
  278. }
  279. return state, nil
  280. }
  281. // Backfill sequentially fetches, verifies and stores light blocks in reverse
  282. // order. It does not stop verifying blocks until reaching a block with a height
  283. // and time that is less or equal to the stopHeight and stopTime. The
  284. // trustedBlockID should be of the header at startHeight.
  285. func (r *Reactor) Backfill(ctx context.Context, state sm.State) error {
  286. params := state.ConsensusParams.Evidence
  287. stopHeight := state.LastBlockHeight - params.MaxAgeNumBlocks
  288. stopTime := state.LastBlockTime.Add(-params.MaxAgeDuration)
  289. // ensure that stop height doesn't go below the initial height
  290. if stopHeight < state.InitialHeight {
  291. stopHeight = state.InitialHeight
  292. // this essentially makes stop time a void criteria for termination
  293. stopTime = state.LastBlockTime
  294. }
  295. return r.backfill(
  296. ctx,
  297. state.ChainID,
  298. state.LastBlockHeight,
  299. stopHeight,
  300. state.InitialHeight,
  301. state.LastBlockID,
  302. stopTime,
  303. )
  304. }
  305. func (r *Reactor) backfill(
  306. ctx context.Context,
  307. chainID string,
  308. startHeight, stopHeight, initialHeight int64,
  309. trustedBlockID types.BlockID,
  310. stopTime time.Time,
  311. ) error {
  312. r.logger.Info("starting backfill process...", "startHeight", startHeight,
  313. "stopHeight", stopHeight, "stopTime", stopTime, "trustedBlockID", trustedBlockID)
  314. r.backfillBlockTotal = startHeight - stopHeight + 1
  315. r.metrics.BackFillBlocksTotal.Set(float64(r.backfillBlockTotal))
  316. const sleepTime = 1 * time.Second
  317. var (
  318. lastValidatorSet *types.ValidatorSet
  319. lastChangeHeight = startHeight
  320. )
  321. queue := newBlockQueue(startHeight, stopHeight, initialHeight, stopTime, maxLightBlockRequestRetries)
  322. // fetch light blocks across four workers. The aim with deploying concurrent
  323. // workers is to equate the network messaging time with the verification
  324. // time. Ideally we want the verification process to never have to be
  325. // waiting on blocks. If it takes 4s to retrieve a block and 1s to verify
  326. // it, then steady state involves four workers.
  327. for i := 0; i < int(r.cfg.Fetchers); i++ {
  328. ctxWithCancel, cancel := context.WithCancel(ctx)
  329. defer cancel()
  330. go func() {
  331. for {
  332. select {
  333. case <-ctx.Done():
  334. return
  335. case height := <-queue.nextHeight():
  336. // pop the next peer of the list to send a request to
  337. peer := r.peers.Pop(ctx)
  338. r.logger.Debug("fetching next block", "height", height, "peer", peer)
  339. subCtx, cancel := context.WithTimeout(ctxWithCancel, lightBlockResponseTimeout)
  340. defer cancel()
  341. lb, err := func() (*types.LightBlock, error) {
  342. defer cancel()
  343. // request the light block with a timeout
  344. return r.dispatcher.LightBlock(subCtx, height, peer)
  345. }()
  346. // once the peer has returned a value, add it back to the peer list to be used again
  347. r.peers.Append(peer)
  348. if errors.Is(err, context.Canceled) {
  349. return
  350. }
  351. if err != nil {
  352. queue.retry(height)
  353. if errors.Is(err, errNoConnectedPeers) {
  354. r.logger.Info("backfill: no connected peers to fetch light blocks from; sleeping...",
  355. "sleepTime", sleepTime)
  356. time.Sleep(sleepTime)
  357. } else {
  358. // we don't punish the peer as it might just have not responded in time
  359. r.logger.Info("backfill: error with fetching light block",
  360. "height", height, "err", err)
  361. }
  362. continue
  363. }
  364. if lb == nil {
  365. r.logger.Info("backfill: peer didn't have block, fetching from another peer", "height", height)
  366. queue.retry(height)
  367. // As we are fetching blocks backwards, if this node doesn't have the block it likely doesn't
  368. // have any prior ones, thus we remove it from the peer list.
  369. r.peers.Remove(peer)
  370. continue
  371. }
  372. // run a validate basic. This checks the validator set and commit
  373. // hashes line up
  374. err = lb.ValidateBasic(chainID)
  375. if err != nil || lb.Height != height {
  376. r.logger.Info("backfill: fetched light block failed validate basic, removing peer...",
  377. "err", err, "height", height)
  378. queue.retry(height)
  379. if serr := r.blockCh.SendError(ctx, p2p.PeerError{
  380. NodeID: peer,
  381. Err: fmt.Errorf("received invalid light block: %w", err),
  382. }); serr != nil {
  383. return
  384. }
  385. continue
  386. }
  387. // add block to queue to be verified
  388. queue.add(lightBlockResponse{
  389. block: lb,
  390. peer: peer,
  391. })
  392. r.logger.Debug("backfill: added light block to processing queue", "height", height)
  393. case <-queue.done():
  394. return
  395. }
  396. }
  397. }()
  398. }
  399. // verify all light blocks
  400. for {
  401. select {
  402. case <-ctx.Done():
  403. queue.close()
  404. return nil
  405. case resp := <-queue.verifyNext():
  406. // validate the header hash. We take the last block id of the
  407. // previous header (i.e. one height above) as the trusted hash which
  408. // we equate to. ValidatorsHash and CommitHash have already been
  409. // checked in the `ValidateBasic`
  410. if w, g := trustedBlockID.Hash, resp.block.Hash(); !bytes.Equal(w, g) {
  411. r.logger.Info("received invalid light block. header hash doesn't match trusted LastBlockID",
  412. "trustedHash", w, "receivedHash", g, "height", resp.block.Height)
  413. if err := r.blockCh.SendError(ctx, p2p.PeerError{
  414. NodeID: resp.peer,
  415. Err: fmt.Errorf("received invalid light block. Expected hash %v, got: %v", w, g),
  416. }); err != nil {
  417. return nil
  418. }
  419. queue.retry(resp.block.Height)
  420. continue
  421. }
  422. // save the signed headers
  423. if err := r.blockStore.SaveSignedHeader(resp.block.SignedHeader, trustedBlockID); err != nil {
  424. return err
  425. }
  426. // check if there has been a change in the validator set
  427. if lastValidatorSet != nil && !bytes.Equal(resp.block.Header.ValidatorsHash, resp.block.Header.NextValidatorsHash) {
  428. // save all the heights that the last validator set was the same
  429. if err := r.stateStore.SaveValidatorSets(resp.block.Height+1, lastChangeHeight, lastValidatorSet); err != nil {
  430. return err
  431. }
  432. // update the lastChangeHeight
  433. lastChangeHeight = resp.block.Height
  434. }
  435. trustedBlockID = resp.block.LastBlockID
  436. queue.success()
  437. r.logger.Info("backfill: verified and stored light block", "height", resp.block.Height)
  438. lastValidatorSet = resp.block.ValidatorSet
  439. r.backfilledBlocks++
  440. r.metrics.BackFilledBlocks.Add(1)
  441. // The block height might be less than the stopHeight because of the stopTime condition
  442. // hasn't been fulfilled.
  443. if resp.block.Height < stopHeight {
  444. r.backfillBlockTotal++
  445. r.metrics.BackFillBlocksTotal.Set(float64(r.backfillBlockTotal))
  446. }
  447. case <-queue.done():
  448. if err := queue.error(); err != nil {
  449. return err
  450. }
  451. // save the final batch of validators
  452. if err := r.stateStore.SaveValidatorSets(queue.terminal.Height, lastChangeHeight, lastValidatorSet); err != nil {
  453. return err
  454. }
  455. r.logger.Info("successfully completed backfill process", "endHeight", queue.terminal.Height)
  456. return nil
  457. }
  458. }
  459. }
  460. // handleSnapshotMessage handles envelopes sent from peers on the
  461. // SnapshotChannel. It returns an error only if the Envelope.Message is unknown
  462. // for this channel. This should never be called outside of handleMessage.
  463. func (r *Reactor) handleSnapshotMessage(ctx context.Context, envelope *p2p.Envelope) error {
  464. logger := r.logger.With("peer", envelope.From)
  465. switch msg := envelope.Message.(type) {
  466. case *ssproto.SnapshotsRequest:
  467. snapshots, err := r.recentSnapshots(ctx, recentSnapshots)
  468. if err != nil {
  469. logger.Error("failed to fetch snapshots", "err", err)
  470. return nil
  471. }
  472. for _, snapshot := range snapshots {
  473. logger.Info(
  474. "advertising snapshot",
  475. "height", snapshot.Height,
  476. "format", snapshot.Format,
  477. "peer", envelope.From,
  478. )
  479. if err := r.snapshotCh.Send(ctx, p2p.Envelope{
  480. To: envelope.From,
  481. Message: &ssproto.SnapshotsResponse{
  482. Height: snapshot.Height,
  483. Format: snapshot.Format,
  484. Chunks: snapshot.Chunks,
  485. Hash: snapshot.Hash,
  486. Metadata: snapshot.Metadata,
  487. },
  488. }); err != nil {
  489. return err
  490. }
  491. }
  492. case *ssproto.SnapshotsResponse:
  493. r.mtx.RLock()
  494. defer r.mtx.RUnlock()
  495. if r.syncer == nil {
  496. logger.Debug("received unexpected snapshot; no state sync in progress")
  497. return nil
  498. }
  499. logger.Info("received snapshot", "height", msg.Height, "format", msg.Format)
  500. _, err := r.syncer.AddSnapshot(envelope.From, &snapshot{
  501. Height: msg.Height,
  502. Format: msg.Format,
  503. Chunks: msg.Chunks,
  504. Hash: msg.Hash,
  505. Metadata: msg.Metadata,
  506. })
  507. if err != nil {
  508. logger.Error(
  509. "failed to add snapshot",
  510. "height", msg.Height,
  511. "format", msg.Format,
  512. "err", err,
  513. "channel", r.snapshotCh.ID,
  514. )
  515. return nil
  516. }
  517. logger.Info("added snapshot", "height", msg.Height, "format", msg.Format)
  518. default:
  519. return fmt.Errorf("received unknown message: %T", msg)
  520. }
  521. return nil
  522. }
  523. // handleChunkMessage handles envelopes sent from peers on the ChunkChannel.
  524. // It returns an error only if the Envelope.Message is unknown for this channel.
  525. // This should never be called outside of handleMessage.
  526. func (r *Reactor) handleChunkMessage(ctx context.Context, envelope *p2p.Envelope) error {
  527. switch msg := envelope.Message.(type) {
  528. case *ssproto.ChunkRequest:
  529. r.logger.Debug(
  530. "received chunk request",
  531. "height", msg.Height,
  532. "format", msg.Format,
  533. "chunk", msg.Index,
  534. "peer", envelope.From,
  535. )
  536. resp, err := r.conn.LoadSnapshotChunkSync(ctx, abci.RequestLoadSnapshotChunk{
  537. Height: msg.Height,
  538. Format: msg.Format,
  539. Chunk: msg.Index,
  540. })
  541. if err != nil {
  542. r.logger.Error(
  543. "failed to load chunk",
  544. "height", msg.Height,
  545. "format", msg.Format,
  546. "chunk", msg.Index,
  547. "err", err,
  548. "peer", envelope.From,
  549. )
  550. return nil
  551. }
  552. r.logger.Debug(
  553. "sending chunk",
  554. "height", msg.Height,
  555. "format", msg.Format,
  556. "chunk", msg.Index,
  557. "peer", envelope.From,
  558. )
  559. if err := r.chunkCh.Send(ctx, p2p.Envelope{
  560. To: envelope.From,
  561. Message: &ssproto.ChunkResponse{
  562. Height: msg.Height,
  563. Format: msg.Format,
  564. Index: msg.Index,
  565. Chunk: resp.Chunk,
  566. Missing: resp.Chunk == nil,
  567. },
  568. }); err != nil {
  569. return err
  570. }
  571. case *ssproto.ChunkResponse:
  572. r.mtx.RLock()
  573. defer r.mtx.RUnlock()
  574. if r.syncer == nil {
  575. r.logger.Debug("received unexpected chunk; no state sync in progress", "peer", envelope.From)
  576. return nil
  577. }
  578. r.logger.Debug(
  579. "received chunk; adding to sync",
  580. "height", msg.Height,
  581. "format", msg.Format,
  582. "chunk", msg.Index,
  583. "peer", envelope.From,
  584. )
  585. _, err := r.syncer.AddChunk(&chunk{
  586. Height: msg.Height,
  587. Format: msg.Format,
  588. Index: msg.Index,
  589. Chunk: msg.Chunk,
  590. Sender: envelope.From,
  591. })
  592. if err != nil {
  593. r.logger.Error(
  594. "failed to add chunk",
  595. "height", msg.Height,
  596. "format", msg.Format,
  597. "chunk", msg.Index,
  598. "err", err,
  599. "peer", envelope.From,
  600. )
  601. return nil
  602. }
  603. default:
  604. return fmt.Errorf("received unknown message: %T", msg)
  605. }
  606. return nil
  607. }
  608. func (r *Reactor) handleLightBlockMessage(ctx context.Context, envelope *p2p.Envelope) error {
  609. switch msg := envelope.Message.(type) {
  610. case *ssproto.LightBlockRequest:
  611. r.logger.Info("received light block request", "height", msg.Height)
  612. lb, err := r.fetchLightBlock(msg.Height)
  613. if err != nil {
  614. r.logger.Error("failed to retrieve light block", "err", err, "height", msg.Height)
  615. return err
  616. }
  617. if lb == nil {
  618. if err := r.blockCh.Send(ctx, p2p.Envelope{
  619. To: envelope.From,
  620. Message: &ssproto.LightBlockResponse{
  621. LightBlock: nil,
  622. },
  623. }); err != nil {
  624. return err
  625. }
  626. return nil
  627. }
  628. lbproto, err := lb.ToProto()
  629. if err != nil {
  630. r.logger.Error("marshaling light block to proto", "err", err)
  631. return nil
  632. }
  633. // NOTE: If we don't have the light block we will send a nil light block
  634. // back to the requested node, indicating that we don't have it.
  635. if err := r.blockCh.Send(ctx, p2p.Envelope{
  636. To: envelope.From,
  637. Message: &ssproto.LightBlockResponse{
  638. LightBlock: lbproto,
  639. },
  640. }); err != nil {
  641. return err
  642. }
  643. case *ssproto.LightBlockResponse:
  644. var height int64
  645. if msg.LightBlock != nil {
  646. height = msg.LightBlock.SignedHeader.Header.Height
  647. }
  648. r.logger.Info("received light block response", "peer", envelope.From, "height", height)
  649. if err := r.dispatcher.Respond(msg.LightBlock, envelope.From); err != nil {
  650. r.logger.Error("error processing light block response", "err", err, "height", height)
  651. }
  652. default:
  653. return fmt.Errorf("received unknown message: %T", msg)
  654. }
  655. return nil
  656. }
  657. func (r *Reactor) handleParamsMessage(ctx context.Context, envelope *p2p.Envelope) error {
  658. switch msg := envelope.Message.(type) {
  659. case *ssproto.ParamsRequest:
  660. r.logger.Debug("received consensus params request", "height", msg.Height)
  661. cp, err := r.stateStore.LoadConsensusParams(int64(msg.Height))
  662. if err != nil {
  663. r.logger.Error("failed to fetch requested consensus params", "err", err, "height", msg.Height)
  664. return nil
  665. }
  666. cpproto := cp.ToProto()
  667. if err := r.paramsCh.Send(ctx, p2p.Envelope{
  668. To: envelope.From,
  669. Message: &ssproto.ParamsResponse{
  670. Height: msg.Height,
  671. ConsensusParams: cpproto,
  672. },
  673. }); err != nil {
  674. return err
  675. }
  676. case *ssproto.ParamsResponse:
  677. r.mtx.RLock()
  678. defer r.mtx.RUnlock()
  679. r.logger.Debug("received consensus params response", "height", msg.Height)
  680. cp := types.ConsensusParamsFromProto(msg.ConsensusParams)
  681. if sp, ok := r.stateProvider.(*stateProviderP2P); ok {
  682. select {
  683. case sp.paramsRecvCh <- cp:
  684. case <-time.After(time.Second):
  685. return errors.New("failed to send consensus params, stateprovider not ready for response")
  686. }
  687. } else {
  688. r.logger.Debug("received unexpected params response; using RPC state provider", "peer", envelope.From)
  689. }
  690. default:
  691. return fmt.Errorf("received unknown message: %T", msg)
  692. }
  693. return nil
  694. }
  695. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  696. // It will handle errors and any possible panics gracefully. A caller can handle
  697. // any error returned by sending a PeerError on the respective channel.
  698. func (r *Reactor) handleMessage(ctx context.Context, chID p2p.ChannelID, envelope *p2p.Envelope) (err error) {
  699. defer func() {
  700. if e := recover(); e != nil {
  701. err = fmt.Errorf("panic in processing message: %v", e)
  702. r.logger.Error(
  703. "recovering from processing message panic",
  704. "err", err,
  705. "stack", string(debug.Stack()),
  706. )
  707. }
  708. }()
  709. r.logger.Debug("received message", "message", reflect.TypeOf(envelope.Message), "peer", envelope.From)
  710. switch chID {
  711. case SnapshotChannel:
  712. err = r.handleSnapshotMessage(ctx, envelope)
  713. case ChunkChannel:
  714. err = r.handleChunkMessage(ctx, envelope)
  715. case LightBlockChannel:
  716. err = r.handleLightBlockMessage(ctx, envelope)
  717. case ParamsChannel:
  718. err = r.handleParamsMessage(ctx, envelope)
  719. default:
  720. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  721. }
  722. return err
  723. }
  724. // processCh routes state sync messages to their respective handlers. Any error
  725. // encountered during message execution will result in a PeerError being sent on
  726. // the respective channel. When the reactor is stopped, we will catch the signal
  727. // and close the p2p Channel gracefully.
  728. func (r *Reactor) processCh(ctx context.Context, ch *p2p.Channel, chName string) {
  729. iter := ch.Receive(ctx)
  730. for iter.Next(ctx) {
  731. envelope := iter.Envelope()
  732. if err := r.handleMessage(ctx, ch.ID, envelope); err != nil {
  733. r.logger.Error("failed to process message",
  734. "err", err,
  735. "channel", chName,
  736. "ch_id", ch.ID,
  737. "envelope", envelope)
  738. if serr := ch.SendError(ctx, p2p.PeerError{
  739. NodeID: envelope.From,
  740. Err: err,
  741. }); serr != nil {
  742. return
  743. }
  744. }
  745. }
  746. }
  747. // processPeerUpdate processes a PeerUpdate, returning an error upon failing to
  748. // handle the PeerUpdate or if a panic is recovered.
  749. func (r *Reactor) processPeerUpdate(ctx context.Context, peerUpdate p2p.PeerUpdate) {
  750. r.logger.Info("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  751. switch peerUpdate.Status {
  752. case p2p.PeerStatusUp:
  753. r.peers.Append(peerUpdate.NodeID)
  754. case p2p.PeerStatusDown:
  755. r.peers.Remove(peerUpdate.NodeID)
  756. }
  757. r.mtx.Lock()
  758. defer r.mtx.Unlock()
  759. if r.syncer == nil {
  760. return
  761. }
  762. switch peerUpdate.Status {
  763. case p2p.PeerStatusUp:
  764. newProvider := NewBlockProvider(peerUpdate.NodeID, r.chainID, r.dispatcher)
  765. r.providers[peerUpdate.NodeID] = newProvider
  766. err := r.syncer.AddPeer(ctx, peerUpdate.NodeID)
  767. if err != nil {
  768. r.logger.Error("error adding peer to syncer", "error", err)
  769. return
  770. }
  771. if sp, ok := r.stateProvider.(*stateProviderP2P); ok {
  772. // we do this in a separate routine to not block whilst waiting for the light client to finish
  773. // whatever call it's currently executing
  774. go sp.addProvider(newProvider)
  775. }
  776. case p2p.PeerStatusDown:
  777. delete(r.providers, peerUpdate.NodeID)
  778. r.syncer.RemovePeer(peerUpdate.NodeID)
  779. }
  780. r.logger.Info("processed peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  781. }
  782. // processPeerUpdates initiates a blocking process where we listen for and handle
  783. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  784. // close the p2p PeerUpdatesCh gracefully.
  785. func (r *Reactor) processPeerUpdates(ctx context.Context) {
  786. for {
  787. select {
  788. case <-ctx.Done():
  789. r.logger.Debug("stopped listening on peer updates channel; closing...")
  790. return
  791. case peerUpdate := <-r.peerUpdates.Updates():
  792. r.processPeerUpdate(ctx, peerUpdate)
  793. }
  794. }
  795. }
  796. // recentSnapshots fetches the n most recent snapshots from the app
  797. func (r *Reactor) recentSnapshots(ctx context.Context, n uint32) ([]*snapshot, error) {
  798. resp, err := r.conn.ListSnapshotsSync(ctx, abci.RequestListSnapshots{})
  799. if err != nil {
  800. return nil, err
  801. }
  802. sort.Slice(resp.Snapshots, func(i, j int) bool {
  803. a := resp.Snapshots[i]
  804. b := resp.Snapshots[j]
  805. switch {
  806. case a.Height > b.Height:
  807. return true
  808. case a.Height == b.Height && a.Format > b.Format:
  809. return true
  810. default:
  811. return false
  812. }
  813. })
  814. snapshots := make([]*snapshot, 0, n)
  815. for i, s := range resp.Snapshots {
  816. if i >= recentSnapshots {
  817. break
  818. }
  819. snapshots = append(snapshots, &snapshot{
  820. Height: s.Height,
  821. Format: s.Format,
  822. Chunks: s.Chunks,
  823. Hash: s.Hash,
  824. Metadata: s.Metadata,
  825. })
  826. }
  827. return snapshots, nil
  828. }
  829. // fetchLightBlock works out whether the node has a light block at a particular
  830. // height and if so returns it so it can be gossiped to peers
  831. func (r *Reactor) fetchLightBlock(height uint64) (*types.LightBlock, error) {
  832. h := int64(height)
  833. blockMeta := r.blockStore.LoadBlockMeta(h)
  834. if blockMeta == nil {
  835. return nil, nil
  836. }
  837. commit := r.blockStore.LoadBlockCommit(h)
  838. if commit == nil {
  839. return nil, nil
  840. }
  841. vals, err := r.stateStore.LoadValidators(h)
  842. if err != nil {
  843. return nil, err
  844. }
  845. if vals == nil {
  846. return nil, nil
  847. }
  848. return &types.LightBlock{
  849. SignedHeader: &types.SignedHeader{
  850. Header: &blockMeta.Header,
  851. Commit: commit,
  852. },
  853. ValidatorSet: vals,
  854. }, nil
  855. }
  856. func (r *Reactor) waitForEnoughPeers(ctx context.Context, numPeers int) error {
  857. startAt := time.Now()
  858. t := time.NewTicker(100 * time.Millisecond)
  859. defer t.Stop()
  860. logT := time.NewTicker(time.Minute)
  861. defer logT.Stop()
  862. var iter int
  863. for r.peers.Len() < numPeers {
  864. iter++
  865. select {
  866. case <-ctx.Done():
  867. return fmt.Errorf("operation canceled while waiting for peers after %.2fs [%d/%d]",
  868. time.Since(startAt).Seconds(), r.peers.Len(), numPeers)
  869. case <-t.C:
  870. continue
  871. case <-logT.C:
  872. r.logger.Info("waiting for sufficient peers to start statesync",
  873. "duration", time.Since(startAt).String(),
  874. "target", numPeers,
  875. "peers", r.peers.Len(),
  876. "iters", iter,
  877. )
  878. continue
  879. }
  880. }
  881. return nil
  882. }
  883. func (r *Reactor) initStateProvider(ctx context.Context, chainID string, initialHeight int64) error {
  884. var err error
  885. to := light.TrustOptions{
  886. Period: r.cfg.TrustPeriod,
  887. Height: r.cfg.TrustHeight,
  888. Hash: r.cfg.TrustHashBytes(),
  889. }
  890. spLogger := r.logger.With("module", "stateprovider")
  891. spLogger.Info("initializing state provider", "trustPeriod", to.Period,
  892. "trustHeight", to.Height, "useP2P", r.cfg.UseP2P)
  893. if r.cfg.UseP2P {
  894. if err := r.waitForEnoughPeers(ctx, 2); err != nil {
  895. return err
  896. }
  897. peers := r.peers.All()
  898. providers := make([]provider.Provider, len(peers))
  899. for idx, p := range peers {
  900. providers[idx] = NewBlockProvider(p, chainID, r.dispatcher)
  901. }
  902. r.stateProvider, err = NewP2PStateProvider(ctx, chainID, initialHeight, providers, to, r.paramsCh, spLogger)
  903. if err != nil {
  904. return fmt.Errorf("failed to initialize P2P state provider: %w", err)
  905. }
  906. } else {
  907. r.stateProvider, err = NewRPCStateProvider(ctx, chainID, initialHeight, r.cfg.RPCServers, to, spLogger)
  908. if err != nil {
  909. return fmt.Errorf("failed to initialize RPC state provider: %w", err)
  910. }
  911. }
  912. return nil
  913. }
  914. func (r *Reactor) TotalSnapshots() int64 {
  915. r.mtx.RLock()
  916. defer r.mtx.RUnlock()
  917. if r.syncer != nil && r.syncer.snapshots != nil {
  918. return int64(len(r.syncer.snapshots.snapshots))
  919. }
  920. return 0
  921. }
  922. func (r *Reactor) ChunkProcessAvgTime() time.Duration {
  923. r.mtx.RLock()
  924. defer r.mtx.RUnlock()
  925. if r.syncer != nil {
  926. return time.Duration(r.syncer.avgChunkTime)
  927. }
  928. return time.Duration(0)
  929. }
  930. func (r *Reactor) SnapshotHeight() int64 {
  931. r.mtx.RLock()
  932. defer r.mtx.RUnlock()
  933. if r.syncer != nil {
  934. return r.syncer.lastSyncedSnapshotHeight
  935. }
  936. return 0
  937. }
  938. func (r *Reactor) SnapshotChunksCount() int64 {
  939. r.mtx.RLock()
  940. defer r.mtx.RUnlock()
  941. if r.syncer != nil && r.syncer.chunks != nil {
  942. return int64(r.syncer.chunks.numChunksReturned())
  943. }
  944. return 0
  945. }
  946. func (r *Reactor) SnapshotChunksTotal() int64 {
  947. r.mtx.RLock()
  948. defer r.mtx.RUnlock()
  949. if r.syncer != nil && r.syncer.processingSnapshot != nil {
  950. return int64(r.syncer.processingSnapshot.Chunks)
  951. }
  952. return 0
  953. }
  954. func (r *Reactor) BackFilledBlocks() int64 {
  955. r.mtx.RLock()
  956. defer r.mtx.RUnlock()
  957. return r.backfilledBlocks
  958. }
  959. func (r *Reactor) BackFillBlocksTotal() int64 {
  960. r.mtx.RLock()
  961. defer r.mtx.RUnlock()
  962. return r.backfillBlockTotal
  963. }