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.

830 lines
23 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/libs/log"
  16. "github.com/tendermint/tendermint/libs/service"
  17. ssproto "github.com/tendermint/tendermint/proto/tendermint/statesync"
  18. "github.com/tendermint/tendermint/proxy"
  19. sm "github.com/tendermint/tendermint/state"
  20. "github.com/tendermint/tendermint/store"
  21. "github.com/tendermint/tendermint/types"
  22. )
  23. var (
  24. _ service.Service = (*Reactor)(nil)
  25. _ p2p.Wrapper = (*ssproto.Message)(nil)
  26. // ChannelShims contains a map of ChannelDescriptorShim objects, where each
  27. // object wraps a reference to a legacy p2p ChannelDescriptor and the corresponding
  28. // p2p proto.Message the new p2p Channel is responsible for handling.
  29. //
  30. //
  31. // TODO: Remove once p2p refactor is complete.
  32. // ref: https://github.com/tendermint/tendermint/issues/5670
  33. ChannelShims = map[p2p.ChannelID]*p2p.ChannelDescriptorShim{
  34. SnapshotChannel: {
  35. MsgType: new(ssproto.Message),
  36. Descriptor: &p2p.ChannelDescriptor{
  37. ID: byte(SnapshotChannel),
  38. Priority: 6,
  39. SendQueueCapacity: 10,
  40. RecvMessageCapacity: snapshotMsgSize,
  41. RecvBufferCapacity: 128,
  42. MaxSendBytes: 400,
  43. },
  44. },
  45. ChunkChannel: {
  46. MsgType: new(ssproto.Message),
  47. Descriptor: &p2p.ChannelDescriptor{
  48. ID: byte(ChunkChannel),
  49. Priority: 3,
  50. SendQueueCapacity: 4,
  51. RecvMessageCapacity: chunkMsgSize,
  52. RecvBufferCapacity: 128,
  53. MaxSendBytes: 400,
  54. },
  55. },
  56. LightBlockChannel: {
  57. MsgType: new(ssproto.Message),
  58. Descriptor: &p2p.ChannelDescriptor{
  59. ID: byte(LightBlockChannel),
  60. Priority: 2,
  61. SendQueueCapacity: 10,
  62. RecvMessageCapacity: lightBlockMsgSize,
  63. RecvBufferCapacity: 128,
  64. MaxSendBytes: 400,
  65. },
  66. },
  67. }
  68. )
  69. const (
  70. // SnapshotChannel exchanges snapshot metadata
  71. SnapshotChannel = p2p.ChannelID(0x60)
  72. // ChunkChannel exchanges chunk contents
  73. ChunkChannel = p2p.ChannelID(0x61)
  74. // LightBlockChannel exchanges light blocks
  75. LightBlockChannel = p2p.ChannelID(0x62)
  76. // recentSnapshots is the number of recent snapshots to send and receive per peer.
  77. recentSnapshots = 10
  78. // snapshotMsgSize is the maximum size of a snapshotResponseMessage
  79. snapshotMsgSize = int(4e6) // ~4MB
  80. // chunkMsgSize is the maximum size of a chunkResponseMessage
  81. chunkMsgSize = int(16e6) // ~16MB
  82. // lightBlockMsgSize is the maximum size of a lightBlockResponseMessage
  83. lightBlockMsgSize = int(1e7) // ~10MB
  84. // lightBlockResponseTimeout is how long the dispatcher waits for a peer to
  85. // return a light block
  86. lightBlockResponseTimeout = 10 * time.Second
  87. // maxLightBlockRequestRetries is the amount of retries acceptable before
  88. // the backfill process aborts
  89. maxLightBlockRequestRetries = 20
  90. )
  91. // Reactor handles state sync, both restoring snapshots for the local node and
  92. // serving snapshots for other nodes.
  93. type Reactor struct {
  94. service.BaseService
  95. cfg config.StateSyncConfig
  96. stateStore sm.Store
  97. blockStore *store.BlockStore
  98. conn proxy.AppConnSnapshot
  99. connQuery proxy.AppConnQuery
  100. tempDir string
  101. snapshotCh *p2p.Channel
  102. chunkCh *p2p.Channel
  103. blockCh *p2p.Channel
  104. peerUpdates *p2p.PeerUpdates
  105. closeCh chan struct{}
  106. dispatcher *dispatcher
  107. // This will only be set when a state sync is in progress. It is used to feed
  108. // received snapshots and chunks into the sync.
  109. mtx tmsync.RWMutex
  110. syncer *syncer
  111. }
  112. // NewReactor returns a reference to a new state sync reactor, which implements
  113. // the service.Service interface. It accepts a logger, connections for snapshots
  114. // and querying, references to p2p Channels and a channel to listen for peer
  115. // updates on. Note, the reactor will close all p2p Channels when stopping.
  116. func NewReactor(
  117. cfg config.StateSyncConfig,
  118. logger log.Logger,
  119. conn proxy.AppConnSnapshot,
  120. connQuery proxy.AppConnQuery,
  121. snapshotCh, chunkCh, blockCh *p2p.Channel,
  122. peerUpdates *p2p.PeerUpdates,
  123. stateStore sm.Store,
  124. blockStore *store.BlockStore,
  125. tempDir string,
  126. ) *Reactor {
  127. r := &Reactor{
  128. cfg: cfg,
  129. conn: conn,
  130. connQuery: connQuery,
  131. snapshotCh: snapshotCh,
  132. chunkCh: chunkCh,
  133. blockCh: blockCh,
  134. peerUpdates: peerUpdates,
  135. closeCh: make(chan struct{}),
  136. tempDir: tempDir,
  137. dispatcher: newDispatcher(blockCh.Out, lightBlockResponseTimeout),
  138. stateStore: stateStore,
  139. blockStore: blockStore,
  140. }
  141. r.BaseService = *service.NewBaseService(logger, "StateSync", r)
  142. return r
  143. }
  144. // OnStart starts separate go routines for each p2p Channel and listens for
  145. // envelopes on each. In addition, it also listens for peer updates and handles
  146. // messages on that p2p channel accordingly. The caller must be sure to execute
  147. // OnStop to ensure the outbound p2p Channels are closed. No error is returned.
  148. func (r *Reactor) OnStart() error {
  149. // Listen for envelopes on the snapshot p2p Channel in a separate go-routine
  150. // as to not block or cause IO contention with the chunk p2p Channel. Note,
  151. // we do not launch a go-routine to handle individual envelopes as to not
  152. // have to deal with bounding workers or pools.
  153. go r.processSnapshotCh()
  154. // Listen for envelopes on the chunk p2p Channel in a separate go-routine
  155. // as to not block or cause IO contention with the snapshot p2p Channel. Note,
  156. // we do not launch a go-routine to handle individual envelopes as to not
  157. // have to deal with bounding workers or pools.
  158. go r.processChunkCh()
  159. go r.processBlockCh()
  160. go r.processPeerUpdates()
  161. r.dispatcher.start()
  162. return nil
  163. }
  164. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  165. // blocking until they all exit.
  166. func (r *Reactor) OnStop() {
  167. // tell the dispatcher to stop sending any more requests
  168. r.dispatcher.stop()
  169. // Close closeCh to signal to all spawned goroutines to gracefully exit. All
  170. // p2p Channels should execute Close().
  171. close(r.closeCh)
  172. // Wait for all p2p Channels to be closed before returning. This ensures we
  173. // can easily reason about synchronization of all p2p Channels and ensure no
  174. // panics will occur.
  175. <-r.snapshotCh.Done()
  176. <-r.chunkCh.Done()
  177. <-r.blockCh.Done()
  178. <-r.peerUpdates.Done()
  179. }
  180. // Sync runs a state sync, fetching snapshots and providing chunks to the
  181. // application. It also saves tendermint state and runs a backfill process to
  182. // retrieve the necessary amount of headers, commits and validators sets to be
  183. // able to process evidence and participate in consensus.
  184. func (r *Reactor) Sync(
  185. ctx context.Context,
  186. stateProvider StateProvider,
  187. discoveryTime time.Duration,
  188. ) (sm.State, error) {
  189. r.mtx.Lock()
  190. if r.syncer != nil {
  191. r.mtx.Unlock()
  192. return sm.State{}, errors.New("a state sync is already in progress")
  193. }
  194. r.syncer = newSyncer(
  195. r.cfg,
  196. r.Logger,
  197. r.conn,
  198. r.connQuery,
  199. stateProvider,
  200. r.snapshotCh.Out,
  201. r.chunkCh.Out,
  202. r.tempDir,
  203. )
  204. r.mtx.Unlock()
  205. requestSnapshotsHook := func() {
  206. // request snapshots from all currently connected peers
  207. r.snapshotCh.Out <- p2p.Envelope{
  208. Broadcast: true,
  209. Message: &ssproto.SnapshotsRequest{},
  210. }
  211. }
  212. state, commit, err := r.syncer.SyncAny(ctx, discoveryTime, requestSnapshotsHook)
  213. if err != nil {
  214. return sm.State{}, err
  215. }
  216. r.mtx.Lock()
  217. r.syncer = nil
  218. r.mtx.Unlock()
  219. err = r.stateStore.Bootstrap(state)
  220. if err != nil {
  221. return sm.State{}, fmt.Errorf("failed to bootstrap node with new state: %w", err)
  222. }
  223. err = r.blockStore.SaveSeenCommit(state.LastBlockHeight, commit)
  224. if err != nil {
  225. return sm.State{}, fmt.Errorf("failed to store last seen commit: %w", err)
  226. }
  227. return state, nil
  228. }
  229. // Backfill sequentially fetches, verifies and stores light blocks in reverse
  230. // order. It does not stop verifying blocks until reaching a block with a height
  231. // and time that is less or equal to the stopHeight and stopTime. The
  232. // trustedBlockID should be of the header at startHeight.
  233. func (r *Reactor) Backfill(state sm.State) error {
  234. params := state.ConsensusParams.Evidence
  235. stopHeight := state.LastBlockHeight - params.MaxAgeNumBlocks
  236. stopTime := state.LastBlockTime.Add(-params.MaxAgeDuration)
  237. // ensure that stop height doesn't go below the initial height
  238. if stopHeight < state.InitialHeight {
  239. stopHeight = state.InitialHeight
  240. // this essentially makes stop time a void criteria for termination
  241. stopTime = state.LastBlockTime
  242. }
  243. return r.backfill(
  244. context.Background(),
  245. state.ChainID,
  246. state.LastBlockHeight, stopHeight,
  247. state.LastBlockID,
  248. stopTime,
  249. )
  250. }
  251. func (r *Reactor) backfill(
  252. ctx context.Context,
  253. chainID string,
  254. startHeight, stopHeight int64,
  255. trustedBlockID types.BlockID,
  256. stopTime time.Time,
  257. ) error {
  258. r.Logger.Info("starting backfill process...", "startHeight", startHeight,
  259. "stopHeight", stopHeight, "trustedBlockID", trustedBlockID)
  260. const sleepTime = 1 * time.Second
  261. var (
  262. lastValidatorSet *types.ValidatorSet
  263. lastChangeHeight int64 = startHeight
  264. )
  265. queue := newBlockQueue(startHeight, stopHeight, stopTime, maxLightBlockRequestRetries)
  266. // fetch light blocks across four workers. The aim with deploying concurrent
  267. // workers is to equate the network messaging time with the verification
  268. // time. Ideally we want the verification process to never have to be
  269. // waiting on blocks. If it takes 4s to retrieve a block and 1s to verify
  270. // it, then steady state involves four workers.
  271. for i := 0; i < int(r.cfg.Fetchers); i++ {
  272. ctxWithCancel, cancel := context.WithCancel(ctx)
  273. defer cancel()
  274. go func() {
  275. for {
  276. select {
  277. case height := <-queue.nextHeight():
  278. r.Logger.Debug("fetching next block", "height", height)
  279. lb, peer, err := r.dispatcher.LightBlock(ctxWithCancel, height)
  280. if errors.Is(err, context.Canceled) {
  281. return
  282. }
  283. if err != nil {
  284. queue.retry(height)
  285. if errors.Is(err, errNoConnectedPeers) {
  286. r.Logger.Info("backfill: no connected peers to fetch light blocks from; sleeping...",
  287. "sleepTime", sleepTime)
  288. time.Sleep(sleepTime)
  289. } else {
  290. // we don't punish the peer as it might just have not responded in time
  291. r.Logger.Info("backfill: error with fetching light block",
  292. "height", height, "err", err)
  293. }
  294. continue
  295. }
  296. if lb == nil {
  297. r.Logger.Info("backfill: peer didn't have block, fetching from another peer", "height", height)
  298. queue.retry(height)
  299. // as we are fetching blocks backwards, if this node doesn't have the block it likely doesn't
  300. // have any prior ones, thus we remove it from the peer list
  301. r.dispatcher.removePeer(peer)
  302. continue
  303. }
  304. // run a validate basic. This checks the validator set and commit
  305. // hashes line up
  306. err = lb.ValidateBasic(chainID)
  307. if err != nil || lb.Height != height {
  308. r.Logger.Info("backfill: fetched light block failed validate basic, removing peer...",
  309. "err", err, "height", height)
  310. queue.retry(height)
  311. r.blockCh.Error <- p2p.PeerError{
  312. NodeID: peer,
  313. Err: fmt.Errorf("received invalid light block: %w", err),
  314. }
  315. continue
  316. }
  317. // add block to queue to be verified
  318. queue.add(lightBlockResponse{
  319. block: lb,
  320. peer: peer,
  321. })
  322. r.Logger.Debug("backfill: added light block to processing queue", "height", height)
  323. case <-queue.done():
  324. return
  325. }
  326. }
  327. }()
  328. }
  329. // verify all light blocks
  330. for {
  331. select {
  332. case <-r.closeCh:
  333. queue.close()
  334. return nil
  335. case <-ctx.Done():
  336. queue.close()
  337. return nil
  338. case resp := <-queue.verifyNext():
  339. // validate the header hash. We take the last block id of the
  340. // previous header (i.e. one height above) as the trusted hash which
  341. // we equate to. ValidatorsHash and CommitHash have already been
  342. // checked in the `ValidateBasic`
  343. if w, g := trustedBlockID.Hash, resp.block.Hash(); !bytes.Equal(w, g) {
  344. r.Logger.Info("received invalid light block. header hash doesn't match trusted LastBlockID",
  345. "trustedHash", w, "receivedHash", g, "height", resp.block.Height)
  346. r.blockCh.Error <- p2p.PeerError{
  347. NodeID: resp.peer,
  348. Err: fmt.Errorf("received invalid light block. Expected hash %v, got: %v", w, g),
  349. }
  350. queue.retry(resp.block.Height)
  351. continue
  352. }
  353. // save the signed headers
  354. err := r.blockStore.SaveSignedHeader(resp.block.SignedHeader, trustedBlockID)
  355. if err != nil {
  356. return err
  357. }
  358. // check if there has been a change in the validator set
  359. if lastValidatorSet != nil && !bytes.Equal(resp.block.Header.ValidatorsHash, resp.block.Header.NextValidatorsHash) {
  360. // save all the heights that the last validator set was the same
  361. err = r.stateStore.SaveValidatorSets(resp.block.Height+1, lastChangeHeight, lastValidatorSet)
  362. if err != nil {
  363. return err
  364. }
  365. // update the lastChangeHeight
  366. lastChangeHeight = resp.block.Height
  367. }
  368. trustedBlockID = resp.block.LastBlockID
  369. queue.success(resp.block.Height)
  370. r.Logger.Info("backfill: verified and stored light block", "height", resp.block.Height)
  371. lastValidatorSet = resp.block.ValidatorSet
  372. case <-queue.done():
  373. if err := queue.error(); err != nil {
  374. return err
  375. }
  376. // save the final batch of validators
  377. if err := r.stateStore.SaveValidatorSets(queue.terminal.Height, lastChangeHeight, lastValidatorSet); err != nil {
  378. return err
  379. }
  380. r.Logger.Info("successfully completed backfill process", "endHeight", queue.terminal.Height)
  381. return nil
  382. }
  383. }
  384. }
  385. // Dispatcher exposes the dispatcher so that a state provider can use it for
  386. // light client verification
  387. func (r *Reactor) Dispatcher() *dispatcher { //nolint:golint
  388. return r.dispatcher
  389. }
  390. // handleSnapshotMessage handles envelopes sent from peers on the
  391. // SnapshotChannel. It returns an error only if the Envelope.Message is unknown
  392. // for this channel. This should never be called outside of handleMessage.
  393. func (r *Reactor) handleSnapshotMessage(envelope p2p.Envelope) error {
  394. logger := r.Logger.With("peer", envelope.From)
  395. switch msg := envelope.Message.(type) {
  396. case *ssproto.SnapshotsRequest:
  397. snapshots, err := r.recentSnapshots(recentSnapshots)
  398. if err != nil {
  399. logger.Error("failed to fetch snapshots", "err", err)
  400. return nil
  401. }
  402. for _, snapshot := range snapshots {
  403. logger.Debug(
  404. "advertising snapshot",
  405. "height", snapshot.Height,
  406. "format", snapshot.Format,
  407. )
  408. r.snapshotCh.Out <- p2p.Envelope{
  409. To: envelope.From,
  410. Message: &ssproto.SnapshotsResponse{
  411. Height: snapshot.Height,
  412. Format: snapshot.Format,
  413. Chunks: snapshot.Chunks,
  414. Hash: snapshot.Hash,
  415. Metadata: snapshot.Metadata,
  416. },
  417. }
  418. }
  419. case *ssproto.SnapshotsResponse:
  420. r.mtx.RLock()
  421. defer r.mtx.RUnlock()
  422. if r.syncer == nil {
  423. logger.Debug("received unexpected snapshot; no state sync in progress")
  424. return nil
  425. }
  426. logger.Debug("received snapshot", "height", msg.Height, "format", msg.Format)
  427. _, err := r.syncer.AddSnapshot(envelope.From, &snapshot{
  428. Height: msg.Height,
  429. Format: msg.Format,
  430. Chunks: msg.Chunks,
  431. Hash: msg.Hash,
  432. Metadata: msg.Metadata,
  433. })
  434. if err != nil {
  435. logger.Error(
  436. "failed to add snapshot",
  437. "height", msg.Height,
  438. "format", msg.Format,
  439. "err", err,
  440. "channel", r.snapshotCh.ID,
  441. )
  442. return nil
  443. }
  444. default:
  445. return fmt.Errorf("received unknown message: %T", msg)
  446. }
  447. return nil
  448. }
  449. // handleChunkMessage handles envelopes sent from peers on the ChunkChannel.
  450. // It returns an error only if the Envelope.Message is unknown for this channel.
  451. // This should never be called outside of handleMessage.
  452. func (r *Reactor) handleChunkMessage(envelope p2p.Envelope) error {
  453. switch msg := envelope.Message.(type) {
  454. case *ssproto.ChunkRequest:
  455. r.Logger.Debug(
  456. "received chunk request",
  457. "height", msg.Height,
  458. "format", msg.Format,
  459. "chunk", msg.Index,
  460. "peer", envelope.From,
  461. )
  462. resp, err := r.conn.LoadSnapshotChunkSync(context.Background(), abci.RequestLoadSnapshotChunk{
  463. Height: msg.Height,
  464. Format: msg.Format,
  465. Chunk: msg.Index,
  466. })
  467. if err != nil {
  468. r.Logger.Error(
  469. "failed to load chunk",
  470. "height", msg.Height,
  471. "format", msg.Format,
  472. "chunk", msg.Index,
  473. "err", err,
  474. "peer", envelope.From,
  475. )
  476. return nil
  477. }
  478. r.Logger.Debug(
  479. "sending chunk",
  480. "height", msg.Height,
  481. "format", msg.Format,
  482. "chunk", msg.Index,
  483. "peer", envelope.From,
  484. )
  485. r.chunkCh.Out <- p2p.Envelope{
  486. To: envelope.From,
  487. Message: &ssproto.ChunkResponse{
  488. Height: msg.Height,
  489. Format: msg.Format,
  490. Index: msg.Index,
  491. Chunk: resp.Chunk,
  492. Missing: resp.Chunk == nil,
  493. },
  494. }
  495. case *ssproto.ChunkResponse:
  496. r.mtx.RLock()
  497. defer r.mtx.RUnlock()
  498. if r.syncer == nil {
  499. r.Logger.Debug("received unexpected chunk; no state sync in progress", "peer", envelope.From)
  500. return nil
  501. }
  502. r.Logger.Debug(
  503. "received chunk; adding to sync",
  504. "height", msg.Height,
  505. "format", msg.Format,
  506. "chunk", msg.Index,
  507. "peer", envelope.From,
  508. )
  509. _, err := r.syncer.AddChunk(&chunk{
  510. Height: msg.Height,
  511. Format: msg.Format,
  512. Index: msg.Index,
  513. Chunk: msg.Chunk,
  514. Sender: envelope.From,
  515. })
  516. if err != nil {
  517. r.Logger.Error(
  518. "failed to add chunk",
  519. "height", msg.Height,
  520. "format", msg.Format,
  521. "chunk", msg.Index,
  522. "err", err,
  523. "peer", envelope.From,
  524. )
  525. return nil
  526. }
  527. default:
  528. return fmt.Errorf("received unknown message: %T", msg)
  529. }
  530. return nil
  531. }
  532. func (r *Reactor) handleLightBlockMessage(envelope p2p.Envelope) error {
  533. switch msg := envelope.Message.(type) {
  534. case *ssproto.LightBlockRequest:
  535. r.Logger.Info("received light block request", "height", msg.Height)
  536. lb, err := r.fetchLightBlock(msg.Height)
  537. if err != nil {
  538. r.Logger.Error("failed to retrieve light block", "err", err, "height", msg.Height)
  539. return err
  540. }
  541. lbproto, err := lb.ToProto()
  542. if err != nil {
  543. r.Logger.Error("marshaling light block to proto", "err", err)
  544. return nil
  545. }
  546. // NOTE: If we don't have the light block we will send a nil light block
  547. // back to the requested node, indicating that we don't have it.
  548. r.blockCh.Out <- p2p.Envelope{
  549. To: envelope.From,
  550. Message: &ssproto.LightBlockResponse{
  551. LightBlock: lbproto,
  552. },
  553. }
  554. case *ssproto.LightBlockResponse:
  555. if err := r.dispatcher.respond(msg.LightBlock, envelope.From); err != nil {
  556. r.Logger.Error("error processing light block response", "err", err)
  557. return err
  558. }
  559. default:
  560. return fmt.Errorf("received unknown message: %T", msg)
  561. }
  562. return nil
  563. }
  564. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  565. // It will handle errors and any possible panics gracefully. A caller can handle
  566. // any error returned by sending a PeerError on the respective channel.
  567. func (r *Reactor) handleMessage(chID p2p.ChannelID, envelope p2p.Envelope) (err error) {
  568. defer func() {
  569. if e := recover(); e != nil {
  570. err = fmt.Errorf("panic in processing message: %v", e)
  571. r.Logger.Error(
  572. "recovering from processing message panic",
  573. "err", err,
  574. "stack", string(debug.Stack()),
  575. )
  576. }
  577. }()
  578. r.Logger.Debug("received message", "message", reflect.TypeOf(envelope.Message), "peer", envelope.From)
  579. switch chID {
  580. case SnapshotChannel:
  581. err = r.handleSnapshotMessage(envelope)
  582. case ChunkChannel:
  583. err = r.handleChunkMessage(envelope)
  584. case LightBlockChannel:
  585. err = r.handleLightBlockMessage(envelope)
  586. default:
  587. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  588. }
  589. return err
  590. }
  591. // processSnapshotCh initiates a blocking process where we listen for and handle
  592. // envelopes on the SnapshotChannel.
  593. func (r *Reactor) processSnapshotCh() {
  594. r.processCh(r.snapshotCh, "snapshot")
  595. }
  596. // processChunkCh initiates a blocking process where we listen for and handle
  597. // envelopes on the ChunkChannel.
  598. func (r *Reactor) processChunkCh() {
  599. r.processCh(r.chunkCh, "chunk")
  600. }
  601. // processBlockCh initiates a blocking process where we listen for and handle
  602. // envelopes on the LightBlockChannel.
  603. func (r *Reactor) processBlockCh() {
  604. r.processCh(r.blockCh, "light block")
  605. }
  606. // processCh routes state sync messages to their respective handlers. Any error
  607. // encountered during message execution will result in a PeerError being sent on
  608. // the respective channel. When the reactor is stopped, we will catch the signal
  609. // and close the p2p Channel gracefully.
  610. func (r *Reactor) processCh(ch *p2p.Channel, chName string) {
  611. defer ch.Close()
  612. for {
  613. select {
  614. case envelope := <-ch.In:
  615. if err := r.handleMessage(ch.ID, envelope); err != nil {
  616. r.Logger.Error(fmt.Sprintf("failed to process %s message", chName),
  617. "ch_id", ch.ID, "envelope", envelope, "err", err)
  618. ch.Error <- p2p.PeerError{
  619. NodeID: envelope.From,
  620. Err: err,
  621. }
  622. }
  623. case <-r.closeCh:
  624. r.Logger.Debug(fmt.Sprintf("stopped listening on %s channel; closing...", chName))
  625. return
  626. }
  627. }
  628. }
  629. // processPeerUpdate processes a PeerUpdate, returning an error upon failing to
  630. // handle the PeerUpdate or if a panic is recovered.
  631. func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
  632. r.Logger.Debug("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  633. r.mtx.RLock()
  634. defer r.mtx.RUnlock()
  635. switch peerUpdate.Status {
  636. case p2p.PeerStatusUp:
  637. if r.syncer != nil {
  638. r.syncer.AddPeer(peerUpdate.NodeID)
  639. }
  640. r.dispatcher.addPeer(peerUpdate.NodeID)
  641. case p2p.PeerStatusDown:
  642. if r.syncer != nil {
  643. r.syncer.RemovePeer(peerUpdate.NodeID)
  644. }
  645. r.dispatcher.removePeer(peerUpdate.NodeID)
  646. }
  647. }
  648. // processPeerUpdates initiates a blocking process where we listen for and handle
  649. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  650. // close the p2p PeerUpdatesCh gracefully.
  651. func (r *Reactor) processPeerUpdates() {
  652. defer r.peerUpdates.Close()
  653. for {
  654. select {
  655. case peerUpdate := <-r.peerUpdates.Updates():
  656. r.processPeerUpdate(peerUpdate)
  657. case <-r.closeCh:
  658. r.Logger.Debug("stopped listening on peer updates channel; closing...")
  659. return
  660. }
  661. }
  662. }
  663. // recentSnapshots fetches the n most recent snapshots from the app
  664. func (r *Reactor) recentSnapshots(n uint32) ([]*snapshot, error) {
  665. resp, err := r.conn.ListSnapshotsSync(context.Background(), abci.RequestListSnapshots{})
  666. if err != nil {
  667. return nil, err
  668. }
  669. sort.Slice(resp.Snapshots, func(i, j int) bool {
  670. a := resp.Snapshots[i]
  671. b := resp.Snapshots[j]
  672. switch {
  673. case a.Height > b.Height:
  674. return true
  675. case a.Height == b.Height && a.Format > b.Format:
  676. return true
  677. default:
  678. return false
  679. }
  680. })
  681. snapshots := make([]*snapshot, 0, n)
  682. for i, s := range resp.Snapshots {
  683. if i >= recentSnapshots {
  684. break
  685. }
  686. snapshots = append(snapshots, &snapshot{
  687. Height: s.Height,
  688. Format: s.Format,
  689. Chunks: s.Chunks,
  690. Hash: s.Hash,
  691. Metadata: s.Metadata,
  692. })
  693. }
  694. return snapshots, nil
  695. }
  696. // fetchLightBlock works out whether the node has a light block at a particular
  697. // height and if so returns it so it can be gossiped to peers
  698. func (r *Reactor) fetchLightBlock(height uint64) (*types.LightBlock, error) {
  699. h := int64(height)
  700. blockMeta := r.blockStore.LoadBlockMeta(h)
  701. if blockMeta == nil {
  702. return nil, nil
  703. }
  704. commit := r.blockStore.LoadBlockCommit(h)
  705. if commit == nil {
  706. return nil, nil
  707. }
  708. vals, err := r.stateStore.LoadValidators(h)
  709. if err != nil {
  710. return nil, err
  711. }
  712. if vals == nil {
  713. return nil, nil
  714. }
  715. return &types.LightBlock{
  716. SignedHeader: &types.SignedHeader{
  717. Header: &blockMeta.Header,
  718. Commit: commit,
  719. },
  720. ValidatorSet: vals,
  721. }, nil
  722. }