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.

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