github.com/phillinzzz/newBsc@v1.1.6/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/phillinzzz/newBsc/common" 27 "github.com/phillinzzz/newBsc/core" 28 "github.com/phillinzzz/newBsc/core/types" 29 "github.com/phillinzzz/newBsc/eth/fetcher" 30 "github.com/phillinzzz/newBsc/eth/protocols/eth" 31 "github.com/phillinzzz/newBsc/log" 32 "github.com/phillinzzz/newBsc/p2p/enode" 33 "github.com/phillinzzz/newBsc/trie" 34 ) 35 36 // ethHandler implements the eth.Backend interface to handle the various network 37 // packets that are sent as replies or broadcasts. 38 type ethHandler handler 39 40 func (h *ethHandler) Chain() *core.BlockChain { return h.chain } 41 func (h *ethHandler) StateBloom() *trie.SyncBloom { return h.stateBloom } 42 func (h *ethHandler) TxPool() eth.TxPool { return h.txpool } 43 44 // RunPeer is invoked when a peer joins on the `eth` protocol. 45 func (h *ethHandler) RunPeer(peer *eth.Peer, hand eth.Handler) error { 46 return (*handler)(h).runEthPeer(peer, hand) 47 } 48 49 // PeerInfo retrieves all known `eth` information about a peer. 50 func (h *ethHandler) PeerInfo(id enode.ID) interface{} { 51 if p := h.peers.peer(id.String()); p != nil { 52 return p.info() 53 } 54 return nil 55 } 56 57 // AcceptTxs retrieves whether transaction processing is enabled on the node 58 // or if inbound transactions should simply be dropped. 59 func (h *ethHandler) AcceptTxs() bool { 60 return atomic.LoadUint32(&h.acceptTxs) == 1 61 } 62 63 // Handle is invoked from a peer's message handler when it receives a new remote 64 // message that the handler couldn't consume and serve itself. 65 func (h *ethHandler) Handle(peer *eth.Peer, packet eth.Packet) error { 66 // Consume any broadcasts and announces, forwarding the rest to the downloader 67 switch packet := packet.(type) { 68 case *eth.BlockHeadersPacket: 69 return h.handleHeaders(peer, *packet) 70 71 case *eth.BlockBodiesPacket: 72 txset, uncleset := packet.Unpack() 73 return h.handleBodies(peer, txset, uncleset) 74 75 case *eth.NodeDataPacket: 76 if err := h.downloader.DeliverNodeData(peer.ID(), *packet); err != nil { 77 log.Debug("Failed to deliver node state data", "err", err) 78 } 79 return nil 80 81 case *eth.ReceiptsPacket: 82 if err := h.downloader.DeliverReceipts(peer.ID(), *packet); err != nil { 83 log.Debug("Failed to deliver receipts", "err", err) 84 } 85 return nil 86 87 case *eth.NewBlockHashesPacket: 88 hashes, numbers := packet.Unpack() 89 return h.handleBlockAnnounces(peer, hashes, numbers) 90 91 case *eth.NewBlockPacket: 92 return h.handleBlockBroadcast(peer, packet.Block, packet.TD) 93 94 case *eth.NewPooledTransactionHashesPacket: 95 return h.txFetcher.Notify(peer.ID(), *packet) 96 97 case *eth.TransactionsPacket: 98 return h.txFetcher.Enqueue(peer.ID(), *packet, false) 99 100 case *eth.PooledTransactionsPacket: 101 return h.txFetcher.Enqueue(peer.ID(), *packet, true) 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 // self support diff sync 195 var diffFetcher fetcher.DiffRequesterFn 196 if h.diffSync { 197 // the peer support diff protocol 198 if ep := h.peers.peer(peer.ID()); ep != nil && ep.diffExt != nil { 199 diffFetcher = ep.diffExt.RequestDiffLayers 200 } 201 } 202 203 for i := 0; i < len(unknownHashes); i++ { 204 h.blockFetcher.Notify(peer.ID(), unknownHashes[i], unknownNumbers[i], time.Now(), peer.RequestOneHeader, peer.RequestBodies, diffFetcher) 205 } 206 return nil 207 } 208 209 // handleBlockBroadcast is invoked from a peer's message handler when it transmits a 210 // block broadcast for the local node to process. 211 func (h *ethHandler) handleBlockBroadcast(peer *eth.Peer, block *types.Block, td *big.Int) error { 212 // Schedule the block for import 213 h.blockFetcher.Enqueue(peer.ID(), block) 214 215 // Assuming the block is importable by the peer, but possibly not yet done so, 216 // calculate the head hash and TD that the peer truly must have. 217 var ( 218 trueHead = block.ParentHash() 219 trueTD = new(big.Int).Sub(td, block.Difficulty()) 220 ) 221 // Update the peer's total difficulty if better than the previous 222 if _, td := peer.Head(); trueTD.Cmp(td) > 0 { 223 peer.SetHead(trueHead, trueTD) 224 h.chainSync.handlePeerEvent(peer) 225 } 226 return nil 227 }