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.

1102 lines
31 KiB

  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. "github.com/tendermint/tendermint/libs/log"
  17. "github.com/tendermint/tendermint/libs/service"
  18. "github.com/tendermint/tendermint/light"
  19. "github.com/tendermint/tendermint/light/provider"
  20. ssproto "github.com/tendermint/tendermint/proto/tendermint/statesync"
  21. sm "github.com/tendermint/tendermint/state"
  22. "github.com/tendermint/tendermint/store"
  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.snapshotCh.Done()
  224. <-r.chunkCh.Done()
  225. <-r.blockCh.Done()
  226. <-r.paramsCh.Done()
  227. <-r.peerUpdates.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. r.waitForEnoughPeers(ctx, 2)
  238. r.mtx.Lock()
  239. if r.syncer != nil {
  240. r.mtx.Unlock()
  241. return sm.State{}, errors.New("a state sync is already in progress")
  242. }
  243. if err := r.initStateProvider(ctx, r.chainID, r.initialHeight); err != nil {
  244. return sm.State{}, err
  245. }
  246. r.syncer = newSyncer(
  247. r.cfg,
  248. r.Logger,
  249. r.conn,
  250. r.connQuery,
  251. r.stateProvider,
  252. r.snapshotCh.Out,
  253. r.chunkCh.Out,
  254. r.tempDir,
  255. r.metrics,
  256. )
  257. r.mtx.Unlock()
  258. defer func() {
  259. r.mtx.Lock()
  260. // reset syncing objects at the close of Sync
  261. r.syncer = nil
  262. r.stateProvider = nil
  263. r.mtx.Unlock()
  264. }()
  265. requestSnapshotsHook := func() {
  266. // request snapshots from all currently connected peers
  267. r.snapshotCh.Out <- p2p.Envelope{
  268. Broadcast: true,
  269. Message: &ssproto.SnapshotsRequest{},
  270. }
  271. }
  272. state, commit, err := r.syncer.SyncAny(ctx, r.cfg.DiscoveryTime, requestSnapshotsHook)
  273. if err != nil {
  274. return sm.State{}, err
  275. }
  276. err = r.stateStore.Bootstrap(state)
  277. if err != nil {
  278. return sm.State{}, fmt.Errorf("failed to bootstrap node with new state: %w", err)
  279. }
  280. err = r.blockStore.SaveSeenCommit(state.LastBlockHeight, commit)
  281. if err != nil {
  282. return sm.State{}, fmt.Errorf("failed to store last seen commit: %w", err)
  283. }
  284. err = r.Backfill(ctx, state)
  285. if err != nil {
  286. r.Logger.Error("backfill failed. Proceeding optimistically...", "err", err)
  287. }
  288. return state, nil
  289. }
  290. // Backfill sequentially fetches, verifies and stores light blocks in reverse
  291. // order. It does not stop verifying blocks until reaching a block with a height
  292. // and time that is less or equal to the stopHeight and stopTime. The
  293. // trustedBlockID should be of the header at startHeight.
  294. func (r *Reactor) Backfill(ctx context.Context, state sm.State) error {
  295. params := state.ConsensusParams.Evidence
  296. stopHeight := state.LastBlockHeight - params.MaxAgeNumBlocks
  297. stopTime := state.LastBlockTime.Add(-params.MaxAgeDuration)
  298. // ensure that stop height doesn't go below the initial height
  299. if stopHeight < state.InitialHeight {
  300. stopHeight = state.InitialHeight
  301. // this essentially makes stop time a void criteria for termination
  302. stopTime = state.LastBlockTime
  303. }
  304. return r.backfill(
  305. ctx,
  306. state.ChainID,
  307. state.LastBlockHeight,
  308. stopHeight,
  309. state.InitialHeight,
  310. state.LastBlockID,
  311. stopTime,
  312. )
  313. }
  314. func (r *Reactor) backfill(
  315. ctx context.Context,
  316. chainID string,
  317. startHeight, stopHeight, initialHeight int64,
  318. trustedBlockID types.BlockID,
  319. stopTime time.Time,
  320. ) error {
  321. r.Logger.Info("starting backfill process...", "startHeight", startHeight,
  322. "stopHeight", stopHeight, "stopTime", stopTime, "trustedBlockID", trustedBlockID)
  323. r.backfillBlockTotal = startHeight - stopHeight + 1
  324. r.metrics.BackFillBlocksTotal.Set(float64(r.backfillBlockTotal))
  325. const sleepTime = 1 * time.Second
  326. var (
  327. lastValidatorSet *types.ValidatorSet
  328. lastChangeHeight = startHeight
  329. )
  330. queue := newBlockQueue(startHeight, stopHeight, initialHeight, stopTime, maxLightBlockRequestRetries)
  331. // fetch light blocks across four workers. The aim with deploying concurrent
  332. // workers is to equate the network messaging time with the verification
  333. // time. Ideally we want the verification process to never have to be
  334. // waiting on blocks. If it takes 4s to retrieve a block and 1s to verify
  335. // it, then steady state involves four workers.
  336. for i := 0; i < int(r.cfg.Fetchers); i++ {
  337. ctxWithCancel, cancel := context.WithCancel(ctx)
  338. defer cancel()
  339. go func() {
  340. for {
  341. select {
  342. case height := <-queue.nextHeight():
  343. // pop the next peer of the list to send a request to
  344. peer := r.peers.Pop(ctx)
  345. r.Logger.Debug("fetching next block", "height", height, "peer", peer)
  346. subCtx, cancel := context.WithTimeout(ctxWithCancel, lightBlockResponseTimeout)
  347. defer cancel()
  348. lb, err := func() (*types.LightBlock, error) {
  349. defer cancel()
  350. // request the light block with a timeout
  351. return r.dispatcher.LightBlock(subCtx, height, peer)
  352. }()
  353. // once the peer has returned a value, add it back to the peer list to be used again
  354. r.peers.Append(peer)
  355. if errors.Is(err, context.Canceled) {
  356. return
  357. }
  358. if err != nil {
  359. queue.retry(height)
  360. if errors.Is(err, errNoConnectedPeers) {
  361. r.Logger.Info("backfill: no connected peers to fetch light blocks from; sleeping...",
  362. "sleepTime", sleepTime)
  363. time.Sleep(sleepTime)
  364. } else {
  365. // we don't punish the peer as it might just have not responded in time
  366. r.Logger.Info("backfill: error with fetching light block",
  367. "height", height, "err", err)
  368. }
  369. continue
  370. }
  371. if lb == nil {
  372. r.Logger.Info("backfill: peer didn't have block, fetching from another peer", "height", height)
  373. queue.retry(height)
  374. // As we are fetching blocks backwards, if this node doesn't have the block it likely doesn't
  375. // have any prior ones, thus we remove it from the peer list.
  376. r.peers.Remove(peer)
  377. continue
  378. }
  379. // run a validate basic. This checks the validator set and commit
  380. // hashes line up
  381. err = lb.ValidateBasic(chainID)
  382. if err != nil || lb.Height != height {
  383. r.Logger.Info("backfill: fetched light block failed validate basic, removing peer...",
  384. "err", err, "height", height)
  385. queue.retry(height)
  386. r.blockCh.Error <- p2p.PeerError{
  387. NodeID: peer,
  388. Err: fmt.Errorf("received invalid light block: %w", err),
  389. }
  390. continue
  391. }
  392. // add block to queue to be verified
  393. queue.add(lightBlockResponse{
  394. block: lb,
  395. peer: peer,
  396. })
  397. r.Logger.Debug("backfill: added light block to processing queue", "height", height)
  398. case <-queue.done():
  399. return
  400. }
  401. }
  402. }()
  403. }
  404. // verify all light blocks
  405. for {
  406. select {
  407. case <-r.closeCh:
  408. queue.close()
  409. return nil
  410. case <-ctx.Done():
  411. queue.close()
  412. return nil
  413. case resp := <-queue.verifyNext():
  414. // validate the header hash. We take the last block id of the
  415. // previous header (i.e. one height above) as the trusted hash which
  416. // we equate to. ValidatorsHash and CommitHash have already been
  417. // checked in the `ValidateBasic`
  418. if w, g := trustedBlockID.Hash, resp.block.Hash(); !bytes.Equal(w, g) {
  419. r.Logger.Info("received invalid light block. header hash doesn't match trusted LastBlockID",
  420. "trustedHash", w, "receivedHash", g, "height", resp.block.Height)
  421. r.blockCh.Error <- p2p.PeerError{
  422. NodeID: resp.peer,
  423. Err: fmt.Errorf("received invalid light block. Expected hash %v, got: %v", w, g),
  424. }
  425. queue.retry(resp.block.Height)
  426. continue
  427. }
  428. // save the signed headers
  429. err := r.blockStore.SaveSignedHeader(resp.block.SignedHeader, trustedBlockID)
  430. if err != nil {
  431. return err
  432. }
  433. // check if there has been a change in the validator set
  434. if lastValidatorSet != nil && !bytes.Equal(resp.block.Header.ValidatorsHash, resp.block.Header.NextValidatorsHash) {
  435. // save all the heights that the last validator set was the same
  436. err = r.stateStore.SaveValidatorSets(resp.block.Height+1, lastChangeHeight, lastValidatorSet)
  437. if err != nil {
  438. return err
  439. }
  440. // update the lastChangeHeight
  441. lastChangeHeight = resp.block.Height
  442. }
  443. trustedBlockID = resp.block.LastBlockID
  444. queue.success(resp.block.Height)
  445. r.Logger.Info("backfill: verified and stored light block", "height", resp.block.Height)
  446. lastValidatorSet = resp.block.ValidatorSet
  447. r.backfilledBlocks++
  448. r.metrics.BackFilledBlocks.Add(1)
  449. // The block height might be less than the stopHeight because of the stopTime condition
  450. // hasn't been fulfilled.
  451. if resp.block.Height < stopHeight {
  452. r.backfillBlockTotal++
  453. r.metrics.BackFillBlocksTotal.Set(float64(r.backfillBlockTotal))
  454. }
  455. case <-queue.done():
  456. if err := queue.error(); err != nil {
  457. return err
  458. }
  459. // save the final batch of validators
  460. if err := r.stateStore.SaveValidatorSets(queue.terminal.Height, lastChangeHeight, lastValidatorSet); err != nil {
  461. return err
  462. }
  463. r.Logger.Info("successfully completed backfill process", "endHeight", queue.terminal.Height)
  464. return nil
  465. }
  466. }
  467. }
  468. // handleSnapshotMessage handles envelopes sent from peers on the
  469. // SnapshotChannel. It returns an error only if the Envelope.Message is unknown
  470. // for this channel. This should never be called outside of handleMessage.
  471. func (r *Reactor) handleSnapshotMessage(envelope p2p.Envelope) error {
  472. logger := r.Logger.With("peer", envelope.From)
  473. switch msg := envelope.Message.(type) {
  474. case *ssproto.SnapshotsRequest:
  475. snapshots, err := r.recentSnapshots(recentSnapshots)
  476. if err != nil {
  477. logger.Error("failed to fetch snapshots", "err", err)
  478. return nil
  479. }
  480. for _, snapshot := range snapshots {
  481. logger.Info(
  482. "advertising snapshot",
  483. "height", snapshot.Height,
  484. "format", snapshot.Format,
  485. "peer", envelope.From,
  486. )
  487. r.snapshotCh.Out <- p2p.Envelope{
  488. To: envelope.From,
  489. Message: &ssproto.SnapshotsResponse{
  490. Height: snapshot.Height,
  491. Format: snapshot.Format,
  492. Chunks: snapshot.Chunks,
  493. Hash: snapshot.Hash,
  494. Metadata: snapshot.Metadata,
  495. },
  496. }
  497. }
  498. case *ssproto.SnapshotsResponse:
  499. r.mtx.RLock()
  500. defer r.mtx.RUnlock()
  501. if r.syncer == nil {
  502. logger.Debug("received unexpected snapshot; no state sync in progress")
  503. return nil
  504. }
  505. logger.Info("received snapshot", "height", msg.Height, "format", msg.Format)
  506. _, err := r.syncer.AddSnapshot(envelope.From, &snapshot{
  507. Height: msg.Height,
  508. Format: msg.Format,
  509. Chunks: msg.Chunks,
  510. Hash: msg.Hash,
  511. Metadata: msg.Metadata,
  512. })
  513. if err != nil {
  514. logger.Error(
  515. "failed to add snapshot",
  516. "height", msg.Height,
  517. "format", msg.Format,
  518. "err", err,
  519. "channel", r.snapshotCh.ID,
  520. )
  521. return nil
  522. }
  523. logger.Info("added snapshot", "height", msg.Height, "format", msg.Format)
  524. default:
  525. return fmt.Errorf("received unknown message: %T", msg)
  526. }
  527. return nil
  528. }
  529. // handleChunkMessage handles envelopes sent from peers on the ChunkChannel.
  530. // It returns an error only if the Envelope.Message is unknown for this channel.
  531. // This should never be called outside of handleMessage.
  532. func (r *Reactor) handleChunkMessage(envelope p2p.Envelope) error {
  533. switch msg := envelope.Message.(type) {
  534. case *ssproto.ChunkRequest:
  535. r.Logger.Debug(
  536. "received chunk request",
  537. "height", msg.Height,
  538. "format", msg.Format,
  539. "chunk", msg.Index,
  540. "peer", envelope.From,
  541. )
  542. resp, err := r.conn.LoadSnapshotChunkSync(context.Background(), abci.RequestLoadSnapshotChunk{
  543. Height: msg.Height,
  544. Format: msg.Format,
  545. Chunk: msg.Index,
  546. })
  547. if err != nil {
  548. r.Logger.Error(
  549. "failed to load chunk",
  550. "height", msg.Height,
  551. "format", msg.Format,
  552. "chunk", msg.Index,
  553. "err", err,
  554. "peer", envelope.From,
  555. )
  556. return nil
  557. }
  558. r.Logger.Debug(
  559. "sending chunk",
  560. "height", msg.Height,
  561. "format", msg.Format,
  562. "chunk", msg.Index,
  563. "peer", envelope.From,
  564. )
  565. r.chunkCh.Out <- p2p.Envelope{
  566. To: envelope.From,
  567. Message: &ssproto.ChunkResponse{
  568. Height: msg.Height,
  569. Format: msg.Format,
  570. Index: msg.Index,
  571. Chunk: resp.Chunk,
  572. Missing: resp.Chunk == nil,
  573. },
  574. }
  575. case *ssproto.ChunkResponse:
  576. r.mtx.RLock()
  577. defer r.mtx.RUnlock()
  578. if r.syncer == nil {
  579. r.Logger.Debug("received unexpected chunk; no state sync in progress", "peer", envelope.From)
  580. return nil
  581. }
  582. r.Logger.Debug(
  583. "received chunk; adding to sync",
  584. "height", msg.Height,
  585. "format", msg.Format,
  586. "chunk", msg.Index,
  587. "peer", envelope.From,
  588. )
  589. _, err := r.syncer.AddChunk(&chunk{
  590. Height: msg.Height,
  591. Format: msg.Format,
  592. Index: msg.Index,
  593. Chunk: msg.Chunk,
  594. Sender: envelope.From,
  595. })
  596. if err != nil {
  597. r.Logger.Error(
  598. "failed to add chunk",
  599. "height", msg.Height,
  600. "format", msg.Format,
  601. "chunk", msg.Index,
  602. "err", err,
  603. "peer", envelope.From,
  604. )
  605. return nil
  606. }
  607. default:
  608. return fmt.Errorf("received unknown message: %T", msg)
  609. }
  610. return nil
  611. }
  612. func (r *Reactor) handleLightBlockMessage(envelope p2p.Envelope) error {
  613. switch msg := envelope.Message.(type) {
  614. case *ssproto.LightBlockRequest:
  615. r.Logger.Info("received light block request", "height", msg.Height)
  616. lb, err := r.fetchLightBlock(msg.Height)
  617. if err != nil {
  618. r.Logger.Error("failed to retrieve light block", "err", err, "height", msg.Height)
  619. return err
  620. }
  621. if lb == nil {
  622. r.blockCh.Out <- p2p.Envelope{
  623. To: envelope.From,
  624. Message: &ssproto.LightBlockResponse{
  625. LightBlock: nil,
  626. },
  627. }
  628. return nil
  629. }
  630. lbproto, err := lb.ToProto()
  631. if err != nil {
  632. r.Logger.Error("marshaling light block to proto", "err", err)
  633. return nil
  634. }
  635. // NOTE: If we don't have the light block we will send a nil light block
  636. // back to the requested node, indicating that we don't have it.
  637. r.blockCh.Out <- p2p.Envelope{
  638. To: envelope.From,
  639. Message: &ssproto.LightBlockResponse{
  640. LightBlock: lbproto,
  641. },
  642. }
  643. case *ssproto.LightBlockResponse:
  644. var height int64 = 0
  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(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. r.paramsCh.Out <- p2p.Envelope{
  668. To: envelope.From,
  669. Message: &ssproto.ParamsResponse{
  670. Height: msg.Height,
  671. ConsensusParams: cpproto,
  672. },
  673. }
  674. case *ssproto.ParamsResponse:
  675. r.mtx.RLock()
  676. defer r.mtx.RUnlock()
  677. r.Logger.Debug("received consensus params response", "height", msg.Height)
  678. cp := types.ConsensusParamsFromProto(msg.ConsensusParams)
  679. if sp, ok := r.stateProvider.(*stateProviderP2P); ok {
  680. select {
  681. case sp.paramsRecvCh <- cp:
  682. default:
  683. }
  684. } else {
  685. r.Logger.Debug("received unexpected params response; using RPC state provider", "peer", envelope.From)
  686. }
  687. default:
  688. return fmt.Errorf("received unknown message: %T", msg)
  689. }
  690. return nil
  691. }
  692. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  693. // It will handle errors and any possible panics gracefully. A caller can handle
  694. // any error returned by sending a PeerError on the respective channel.
  695. func (r *Reactor) handleMessage(chID p2p.ChannelID, envelope p2p.Envelope) (err error) {
  696. defer func() {
  697. if e := recover(); e != nil {
  698. err = fmt.Errorf("panic in processing message: %v", e)
  699. r.Logger.Error(
  700. "recovering from processing message panic",
  701. "err", err,
  702. "stack", string(debug.Stack()),
  703. )
  704. }
  705. }()
  706. r.Logger.Debug("received message", "message", reflect.TypeOf(envelope.Message), "peer", envelope.From)
  707. switch chID {
  708. case SnapshotChannel:
  709. err = r.handleSnapshotMessage(envelope)
  710. case ChunkChannel:
  711. err = r.handleChunkMessage(envelope)
  712. case LightBlockChannel:
  713. err = r.handleLightBlockMessage(envelope)
  714. case ParamsChannel:
  715. err = r.handleParamsMessage(envelope)
  716. default:
  717. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  718. }
  719. return err
  720. }
  721. // processSnapshotCh initiates a blocking process where we listen for and handle
  722. // envelopes on the SnapshotChannel.
  723. func (r *Reactor) processSnapshotCh() {
  724. r.processCh(r.snapshotCh, "snapshot")
  725. }
  726. // processChunkCh initiates a blocking process where we listen for and handle
  727. // envelopes on the ChunkChannel.
  728. func (r *Reactor) processChunkCh() {
  729. r.processCh(r.chunkCh, "chunk")
  730. }
  731. // processBlockCh initiates a blocking process where we listen for and handle
  732. // envelopes on the LightBlockChannel.
  733. func (r *Reactor) processBlockCh() {
  734. r.processCh(r.blockCh, "light block")
  735. }
  736. func (r *Reactor) processParamsCh() {
  737. r.processCh(r.paramsCh, "consensus params")
  738. }
  739. // processCh routes state sync messages to their respective handlers. Any error
  740. // encountered during message execution will result in a PeerError being sent on
  741. // the respective channel. When the reactor is stopped, we will catch the signal
  742. // and close the p2p Channel gracefully.
  743. func (r *Reactor) processCh(ch *p2p.Channel, chName string) {
  744. defer ch.Close()
  745. for {
  746. select {
  747. case envelope := <-ch.In:
  748. if err := r.handleMessage(ch.ID, envelope); err != nil {
  749. r.Logger.Error(fmt.Sprintf("failed to process %s message", chName),
  750. "ch_id", ch.ID, "envelope", envelope, "err", err)
  751. ch.Error <- p2p.PeerError{
  752. NodeID: envelope.From,
  753. Err: err,
  754. }
  755. }
  756. case <-r.closeCh:
  757. r.Logger.Debug(fmt.Sprintf("stopped listening on %s channel; closing...", chName))
  758. return
  759. }
  760. }
  761. }
  762. // processPeerUpdate processes a PeerUpdate, returning an error upon failing to
  763. // handle the PeerUpdate or if a panic is recovered.
  764. func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
  765. r.Logger.Info("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  766. switch peerUpdate.Status {
  767. case p2p.PeerStatusUp:
  768. r.peers.Append(peerUpdate.NodeID)
  769. case p2p.PeerStatusDown:
  770. r.peers.Remove(peerUpdate.NodeID)
  771. }
  772. r.mtx.Lock()
  773. if r.syncer == nil {
  774. r.mtx.Unlock()
  775. return
  776. }
  777. defer r.mtx.Unlock()
  778. switch peerUpdate.Status {
  779. case p2p.PeerStatusUp:
  780. newProvider := NewBlockProvider(peerUpdate.NodeID, r.chainID, r.dispatcher)
  781. r.providers[peerUpdate.NodeID] = newProvider
  782. r.syncer.AddPeer(peerUpdate.NodeID)
  783. if sp, ok := r.stateProvider.(*stateProviderP2P); ok {
  784. // we do this in a separate routine to not block whilst waiting for the light client to finish
  785. // whatever call it's currently executing
  786. go sp.addProvider(newProvider)
  787. }
  788. case p2p.PeerStatusDown:
  789. delete(r.providers, peerUpdate.NodeID)
  790. r.syncer.RemovePeer(peerUpdate.NodeID)
  791. }
  792. r.Logger.Info("processed peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  793. }
  794. // processPeerUpdates initiates a blocking process where we listen for and handle
  795. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  796. // close the p2p PeerUpdatesCh gracefully.
  797. func (r *Reactor) processPeerUpdates() {
  798. defer r.peerUpdates.Close()
  799. for {
  800. select {
  801. case peerUpdate := <-r.peerUpdates.Updates():
  802. r.processPeerUpdate(peerUpdate)
  803. case <-r.closeCh:
  804. r.Logger.Debug("stopped listening on peer updates channel; closing...")
  805. return
  806. }
  807. }
  808. }
  809. // recentSnapshots fetches the n most recent snapshots from the app
  810. func (r *Reactor) recentSnapshots(n uint32) ([]*snapshot, error) {
  811. resp, err := r.conn.ListSnapshotsSync(context.Background(), abci.RequestListSnapshots{})
  812. if err != nil {
  813. return nil, err
  814. }
  815. sort.Slice(resp.Snapshots, func(i, j int) bool {
  816. a := resp.Snapshots[i]
  817. b := resp.Snapshots[j]
  818. switch {
  819. case a.Height > b.Height:
  820. return true
  821. case a.Height == b.Height && a.Format > b.Format:
  822. return true
  823. default:
  824. return false
  825. }
  826. })
  827. snapshots := make([]*snapshot, 0, n)
  828. for i, s := range resp.Snapshots {
  829. if i >= recentSnapshots {
  830. break
  831. }
  832. snapshots = append(snapshots, &snapshot{
  833. Height: s.Height,
  834. Format: s.Format,
  835. Chunks: s.Chunks,
  836. Hash: s.Hash,
  837. Metadata: s.Metadata,
  838. })
  839. }
  840. return snapshots, nil
  841. }
  842. // fetchLightBlock works out whether the node has a light block at a particular
  843. // height and if so returns it so it can be gossiped to peers
  844. func (r *Reactor) fetchLightBlock(height uint64) (*types.LightBlock, error) {
  845. h := int64(height)
  846. blockMeta := r.blockStore.LoadBlockMeta(h)
  847. if blockMeta == nil {
  848. return nil, nil
  849. }
  850. commit := r.blockStore.LoadBlockCommit(h)
  851. if commit == nil {
  852. return nil, nil
  853. }
  854. vals, err := r.stateStore.LoadValidators(h)
  855. if err != nil {
  856. return nil, err
  857. }
  858. if vals == nil {
  859. return nil, nil
  860. }
  861. return &types.LightBlock{
  862. SignedHeader: &types.SignedHeader{
  863. Header: &blockMeta.Header,
  864. Commit: commit,
  865. },
  866. ValidatorSet: vals,
  867. }, nil
  868. }
  869. func (r *Reactor) waitForEnoughPeers(ctx context.Context, numPeers int) {
  870. t := time.NewTicker(200 * time.Millisecond)
  871. defer t.Stop()
  872. for {
  873. select {
  874. case <-ctx.Done():
  875. return
  876. case <-t.C:
  877. if r.peers.Len() >= numPeers {
  878. return
  879. }
  880. }
  881. }
  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. peers := r.peers.All()
  895. providers := make([]provider.Provider, len(peers))
  896. for idx, p := range peers {
  897. providers[idx] = NewBlockProvider(p, chainID, r.dispatcher)
  898. }
  899. r.stateProvider, err = NewP2PStateProvider(ctx, chainID, initialHeight, providers, to, r.paramsCh.Out, spLogger)
  900. if err != nil {
  901. return fmt.Errorf("failed to initialize P2P state provider: %w", err)
  902. }
  903. } else {
  904. r.stateProvider, err = NewRPCStateProvider(ctx, chainID, initialHeight, r.cfg.RPCServers, to, spLogger)
  905. if err != nil {
  906. return fmt.Errorf("failed to initialize RPC state provider: %w", err)
  907. }
  908. }
  909. return nil
  910. }
  911. func (r *Reactor) TotalSnapshots() int64 {
  912. r.mtx.RLock()
  913. defer r.mtx.RUnlock()
  914. if r.syncer != nil && r.syncer.snapshots != nil {
  915. return int64(len(r.syncer.snapshots.snapshots))
  916. }
  917. return 0
  918. }
  919. func (r *Reactor) ChunkProcessAvgTime() time.Duration {
  920. r.mtx.RLock()
  921. defer r.mtx.RUnlock()
  922. if r.syncer != nil {
  923. return time.Duration(r.syncer.avgChunkTime)
  924. }
  925. return time.Duration(0)
  926. }
  927. func (r *Reactor) SnapshotHeight() int64 {
  928. r.mtx.RLock()
  929. defer r.mtx.RUnlock()
  930. if r.syncer != nil {
  931. return r.syncer.lastSyncedSnapshotHeight
  932. }
  933. return 0
  934. }
  935. func (r *Reactor) SnapshotChunksCount() int64 {
  936. r.mtx.RLock()
  937. defer r.mtx.RUnlock()
  938. if r.syncer != nil && r.syncer.chunks != nil {
  939. return int64(r.syncer.chunks.numChunksReturned())
  940. }
  941. return 0
  942. }
  943. func (r *Reactor) SnapshotChunksTotal() int64 {
  944. r.mtx.RLock()
  945. defer r.mtx.RUnlock()
  946. if r.syncer != nil && r.syncer.processingSnapshot != nil {
  947. return int64(r.syncer.processingSnapshot.Chunks)
  948. }
  949. return 0
  950. }
  951. func (r *Reactor) BackFilledBlocks() int64 {
  952. r.mtx.RLock()
  953. defer r.mtx.RUnlock()
  954. return r.backfilledBlocks
  955. }
  956. func (r *Reactor) BackFillBlocksTotal() int64 {
  957. r.mtx.RLock()
  958. defer r.mtx.RUnlock()
  959. return r.backfillBlockTotal
  960. }