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