handler_eth.go 8.2 KB

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