handler_eth.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package eth
  17. import (
  18. "errors"
  19. "fmt"
  20. "math/big"
  21. "sync/atomic"
  22. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/eth/protocols/eth"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/p2p/enode"
  29. "github.com/ethereum/go-ethereum/trie"
  30. )
  31. // ethHandler implements the eth.Backend interface to handle the various network
  32. // packets that are sent as replies or broadcasts.
  33. type ethHandler handler
  34. func (h *ethHandler) Chain() *core.BlockChain { return h.chain }
  35. func (h *ethHandler) StateBloom() *trie.SyncBloom { return h.stateBloom }
  36. func (h *ethHandler) TxPool() eth.TxPool { return h.txpool }
  37. // RunPeer is invoked when a peer joins on the `eth` protocol.
  38. func (h *ethHandler) RunPeer(peer *eth.Peer, hand eth.Handler) error {
  39. return (*handler)(h).runEthPeer(peer, hand)
  40. }
  41. // PeerInfo retrieves all known `eth` information about a peer.
  42. func (h *ethHandler) PeerInfo(id enode.ID) interface{} {
  43. if p := h.peers.peer(id.String()); p != nil {
  44. return p.info()
  45. }
  46. return nil
  47. }
  48. // AcceptTxs retrieves whether transaction processing is enabled on the node
  49. // or if inbound transactions should simply be dropped.
  50. func (h *ethHandler) AcceptTxs() bool {
  51. return atomic.LoadUint32(&h.acceptTxs) == 1
  52. }
  53. // Handle is invoked from a peer's message handler when it receives a new remote
  54. // message that the handler couldn't consume and serve itself.
  55. func (h *ethHandler) Handle(peer *eth.Peer, packet eth.Packet) error {
  56. // Consume any broadcasts and announces, forwarding the rest to the downloader
  57. switch packet := packet.(type) {
  58. case *eth.BlockHeadersPacket:
  59. return h.handleHeaders(peer, *packet)
  60. case *eth.BlockBodiesPacket:
  61. txset, uncleset := packet.Unpack()
  62. return h.handleBodies(peer, txset, uncleset)
  63. case *eth.NodeDataPacket:
  64. if err := h.downloader.DeliverNodeData(peer.ID(), *packet); err != nil {
  65. log.Debug("Failed to deliver node state data", "err", err)
  66. }
  67. return nil
  68. case *eth.ReceiptsPacket:
  69. if err := h.downloader.DeliverReceipts(peer.ID(), *packet); err != nil {
  70. log.Debug("Failed to deliver receipts", "err", err)
  71. }
  72. return nil
  73. case *eth.NewBlockHashesPacket:
  74. hashes, numbers := packet.Unpack()
  75. return h.handleBlockAnnounces(peer, hashes, numbers)
  76. case *eth.NewBlockPacket:
  77. return h.handleBlockBroadcast(peer, packet.Block, packet.TD)
  78. case *eth.NewPooledTransactionHashesPacket:
  79. return h.txFetcher.Notify(peer.ID(), *packet)
  80. case *eth.TransactionsPacket:
  81. return h.txFetcher.Enqueue(peer.ID(), *packet, false)
  82. case *eth.PooledTransactionsPacket:
  83. return h.txFetcher.Enqueue(peer.ID(), *packet, true)
  84. default:
  85. return fmt.Errorf("unexpected eth packet type: %T", packet)
  86. }
  87. }
  88. // handleHeaders is invoked from a peer's message handler when it transmits a batch
  89. // of headers for the local node to process.
  90. func (h *ethHandler) handleHeaders(peer *eth.Peer, headers []*types.Header) error {
  91. p := h.peers.peer(peer.ID())
  92. if p == nil {
  93. return errors.New("unregistered during callback")
  94. }
  95. // If no headers were received, but we're expencting a checkpoint header, consider it that
  96. if len(headers) == 0 && p.syncDrop != nil {
  97. // Stop the timer either way, decide later to drop or not
  98. p.syncDrop.Stop()
  99. p.syncDrop = nil
  100. // If we're doing a fast (or snap) sync, we must enforce the checkpoint block to avoid
  101. // eclipse attacks. Unsynced nodes are welcome to connect after we're done
  102. // joining the network
  103. if atomic.LoadUint32(&h.fastSync) == 1 {
  104. peer.Log().Warn("Dropping unsynced node during sync", "addr", peer.RemoteAddr(), "type", peer.Name())
  105. return errors.New("unsynced node cannot serve sync")
  106. }
  107. }
  108. // Filter out any explicitly requested headers, deliver the rest to the downloader
  109. filter := len(headers) == 1
  110. if filter {
  111. // If it's a potential sync progress check, validate the content and advertised chain weight
  112. if p.syncDrop != nil && headers[0].Number.Uint64() == h.checkpointNumber {
  113. // Disable the sync drop timer
  114. p.syncDrop.Stop()
  115. p.syncDrop = nil
  116. // Validate the header and either drop the peer or continue
  117. if headers[0].Hash() != h.checkpointHash {
  118. return errors.New("checkpoint hash mismatch")
  119. }
  120. return nil
  121. }
  122. // Otherwise if it's a whitelisted block, validate against the set
  123. if want, ok := h.authorizationList[headers[0].Number.Uint64()]; ok {
  124. if hash := headers[0].Hash(); want != hash {
  125. peer.Log().Info("Whitelist mismatch, dropping peer", "number", headers[0].Number.Uint64(), "hash", hash, "want", want)
  126. return errors.New("whitelist block mismatch")
  127. }
  128. peer.Log().Debug("Whitelist block verified", "number", headers[0].Number.Uint64(), "hash", want)
  129. }
  130. // Irrelevant of the fork checks, send the header to the fetcher just in case
  131. headers = h.blockFetcher.FilterHeaders(peer.ID(), headers, time.Now())
  132. }
  133. if len(headers) > 0 || !filter {
  134. err := h.downloader.DeliverHeaders(peer.ID(), headers)
  135. if err != nil {
  136. log.Debug("Failed to deliver headers", "err", err)
  137. }
  138. }
  139. return nil
  140. }
  141. // handleBodies is invoked from a peer's message handler when it transmits a batch
  142. // of block bodies for the local node to process.
  143. func (h *ethHandler) handleBodies(peer *eth.Peer, txs [][]*types.Transaction, uncles [][]*types.Header) error {
  144. // Filter out any explicitly requested bodies, deliver the rest to the downloader
  145. filter := len(txs) > 0 || len(uncles) > 0
  146. if filter {
  147. txs, uncles = h.blockFetcher.FilterBodies(peer.ID(), txs, uncles, time.Now())
  148. }
  149. if len(txs) > 0 || len(uncles) > 0 || !filter {
  150. err := h.downloader.DeliverBodies(peer.ID(), txs, uncles)
  151. if err != nil {
  152. log.Debug("Failed to deliver bodies", "err", err)
  153. }
  154. }
  155. return nil
  156. }
  157. // handleBlockAnnounces is invoked from a peer's message handler when it transmits a
  158. // batch of block announcements for the local node to process.
  159. func (h *ethHandler) handleBlockAnnounces(peer *eth.Peer, hashes []common.Hash, numbers []uint64) error {
  160. // Schedule all the unknown hashes for retrieval
  161. var (
  162. unknownHashes = make([]common.Hash, 0, len(hashes))
  163. unknownNumbers = make([]uint64, 0, len(numbers))
  164. )
  165. for i := 0; i < len(hashes); i++ {
  166. if !h.chain.HasBlock(hashes[i], numbers[i]) {
  167. unknownHashes = append(unknownHashes, hashes[i])
  168. unknownNumbers = append(unknownNumbers, numbers[i])
  169. }
  170. }
  171. for i := 0; i < len(unknownHashes); i++ {
  172. h.blockFetcher.Notify(peer.ID(), unknownHashes[i], unknownNumbers[i], time.Now(), peer.RequestOneHeader, peer.RequestBodies)
  173. }
  174. return nil
  175. }
  176. // handleBlockBroadcast is invoked from a peer's message handler when it transmits a
  177. // block broadcast for the local node to process.
  178. func (h *ethHandler) handleBlockBroadcast(peer *eth.Peer, block *types.Block, td *big.Int) error {
  179. // Schedule the block for import
  180. h.blockFetcher.Enqueue(peer.ID(), block)
  181. // Assuming the block is importable by the peer, but possibly not yet done so,
  182. // calculate the head hash and TD that the peer truly must have.
  183. var (
  184. trueHead = block.ParentHash()
  185. trueTD = new(big.Int).Sub(td, block.Difficulty())
  186. )
  187. // Update the peer's total difficulty if better than the previous
  188. if _, td := peer.Head(); trueTD.Cmp(td) > 0 {
  189. peer.SetHead(trueHead, trueTD)
  190. h.chainSync.handlePeerEvent(peer)
  191. }
  192. return nil
  193. }