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.

819 lines
23 KiB

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