github.com/FUSIONFoundation/efsn@v3.6.2-0.20200916075423-dbb5dd5d2cc7+incompatible/les/handler.go (about) 1 // Copyright 2016 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 les implements the Light Ethereum Subprotocol. 18 package les 19 20 import ( 21 "encoding/binary" 22 "encoding/json" 23 "fmt" 24 "math/big" 25 "net" 26 "sync" 27 "time" 28 29 "github.com/FusionFoundation/efsn/common" 30 "github.com/FusionFoundation/efsn/common/mclock" 31 "github.com/FusionFoundation/efsn/consensus" 32 "github.com/FusionFoundation/efsn/core" 33 "github.com/FusionFoundation/efsn/core/rawdb" 34 "github.com/FusionFoundation/efsn/core/state" 35 "github.com/FusionFoundation/efsn/core/types" 36 "github.com/FusionFoundation/efsn/eth/downloader" 37 "github.com/FusionFoundation/efsn/ethdb" 38 "github.com/FusionFoundation/efsn/event" 39 "github.com/FusionFoundation/efsn/light" 40 "github.com/FusionFoundation/efsn/log" 41 "github.com/FusionFoundation/efsn/p2p" 42 "github.com/FusionFoundation/efsn/p2p/discv5" 43 "github.com/FusionFoundation/efsn/params" 44 "github.com/FusionFoundation/efsn/rlp" 45 "github.com/FusionFoundation/efsn/trie" 46 ) 47 48 const ( 49 softResponseLimit = 2 * 1024 * 1024 // Target maximum size of returned blocks, headers or node data. 50 estHeaderRlpSize = 500 // Approximate size of an RLP encoded block header 51 52 ethVersion = 63 // equivalent eth version for the downloader 53 54 MaxHeaderFetch = 192 // Amount of block headers to be fetched per retrieval request 55 MaxBodyFetch = 32 // Amount of block bodies to be fetched per retrieval request 56 MaxReceiptFetch = 128 // Amount of transaction receipts to allow fetching per request 57 MaxCodeFetch = 64 // Amount of contract codes to allow fetching per request 58 MaxProofsFetch = 64 // Amount of merkle proofs to be fetched per retrieval request 59 MaxHelperTrieProofsFetch = 64 // Amount of merkle proofs to be fetched per retrieval request 60 MaxTxSend = 64 // Amount of transactions to be send per request 61 MaxTxStatus = 256 // Amount of transactions to queried per request 62 63 disableClientRemovePeer = false 64 ) 65 66 func errResp(code errCode, format string, v ...interface{}) error { 67 return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...)) 68 } 69 70 type BlockChain interface { 71 Config() *params.ChainConfig 72 HasHeader(hash common.Hash, number uint64) bool 73 GetHeader(hash common.Hash, number uint64) *types.Header 74 GetHeaderByHash(hash common.Hash) *types.Header 75 CurrentHeader() *types.Header 76 GetTd(hash common.Hash, number uint64) *big.Int 77 State() (*state.StateDB, error) 78 InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) 79 Rollback(chain []common.Hash) 80 GetHeaderByNumber(number uint64) *types.Header 81 GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) 82 Genesis() *types.Block 83 SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription 84 } 85 86 type txPool interface { 87 AddRemotes(txs []*types.Transaction) []error 88 Status(hashes []common.Hash) []core.TxStatus 89 } 90 91 type ProtocolManager struct { 92 lightSync bool 93 txpool txPool 94 txrelay *LesTxRelay 95 networkId uint64 96 chainConfig *params.ChainConfig 97 iConfig *light.IndexerConfig 98 blockchain BlockChain 99 chainDb ethdb.Database 100 odr *LesOdr 101 server *LesServer 102 serverPool *serverPool 103 clientPool *freeClientPool 104 lesTopic discv5.Topic 105 reqDist *requestDistributor 106 retriever *retrieveManager 107 108 downloader *downloader.Downloader 109 fetcher *lightFetcher 110 peers *peerSet 111 maxPeers int 112 113 eventMux *event.TypeMux 114 115 // channels for fetcher, syncer, txsyncLoop 116 newPeerCh chan *peer 117 quitSync chan struct{} 118 noMorePeers chan struct{} 119 120 // wait group is used for graceful shutdowns during downloading 121 // and processing 122 wg *sync.WaitGroup 123 } 124 125 // NewProtocolManager returns a new ethereum sub protocol manager. The Ethereum sub protocol manages peers capable 126 // with the ethereum network. 127 func NewProtocolManager(chainConfig *params.ChainConfig, indexerConfig *light.IndexerConfig, lightSync bool, networkId uint64, mux *event.TypeMux, engine consensus.Engine, peers *peerSet, blockchain BlockChain, txpool txPool, chainDb ethdb.Database, odr *LesOdr, txrelay *LesTxRelay, serverPool *serverPool, quitSync chan struct{}, wg *sync.WaitGroup) (*ProtocolManager, error) { 128 // Create the protocol manager with the base fields 129 manager := &ProtocolManager{ 130 lightSync: lightSync, 131 eventMux: mux, 132 blockchain: blockchain, 133 chainConfig: chainConfig, 134 iConfig: indexerConfig, 135 chainDb: chainDb, 136 odr: odr, 137 networkId: networkId, 138 txpool: txpool, 139 txrelay: txrelay, 140 serverPool: serverPool, 141 peers: peers, 142 newPeerCh: make(chan *peer), 143 quitSync: quitSync, 144 wg: wg, 145 noMorePeers: make(chan struct{}), 146 } 147 if odr != nil { 148 manager.retriever = odr.retriever 149 manager.reqDist = odr.retriever.dist 150 } 151 152 removePeer := manager.removePeer 153 if disableClientRemovePeer { 154 removePeer = func(id string) {} 155 } 156 157 if lightSync { 158 manager.downloader = downloader.New(downloader.LightSync, chainDb, manager.eventMux, nil, blockchain, removePeer) 159 manager.peers.notify((*downloaderPeerNotify)(manager)) 160 manager.fetcher = newLightFetcher(manager) 161 } 162 163 return manager, nil 164 } 165 166 // removePeer initiates disconnection from a peer by removing it from the peer set 167 func (pm *ProtocolManager) removePeer(id string) { 168 pm.peers.Unregister(id) 169 } 170 171 func (pm *ProtocolManager) Start(maxPeers int) { 172 pm.maxPeers = maxPeers 173 174 if pm.lightSync { 175 go pm.syncer() 176 } else { 177 pm.clientPool = newFreeClientPool(pm.chainDb, maxPeers, 10000, mclock.System{}) 178 go func() { 179 for range pm.newPeerCh { 180 } 181 }() 182 } 183 } 184 185 func (pm *ProtocolManager) Stop() { 186 // Showing a log message. During download / process this could actually 187 // take between 5 to 10 seconds and therefor feedback is required. 188 log.Info("Stopping light Ethereum protocol") 189 190 // Quit the sync loop. 191 // After this send has completed, no new peers will be accepted. 192 pm.noMorePeers <- struct{}{} 193 194 close(pm.quitSync) // quits syncer, fetcher 195 if pm.clientPool != nil { 196 pm.clientPool.stop() 197 } 198 199 // Disconnect existing sessions. 200 // This also closes the gate for any new registrations on the peer set. 201 // sessions which are already established but not added to pm.peers yet 202 // will exit when they try to register. 203 pm.peers.Close() 204 205 // Wait for any process action 206 pm.wg.Wait() 207 208 log.Info("Light Ethereum protocol stopped") 209 } 210 211 // runPeer is the p2p protocol run function for the given version. 212 func (pm *ProtocolManager) runPeer(version uint, p *p2p.Peer, rw p2p.MsgReadWriter) error { 213 var entry *poolEntry 214 peer := pm.newPeer(int(version), pm.networkId, p, rw) 215 if pm.serverPool != nil { 216 addr := p.RemoteAddr().(*net.TCPAddr) 217 entry = pm.serverPool.connect(peer, addr.IP, uint16(addr.Port)) 218 } 219 peer.poolEntry = entry 220 select { 221 case pm.newPeerCh <- peer: 222 pm.wg.Add(1) 223 defer pm.wg.Done() 224 err := pm.handle(peer) 225 if entry != nil { 226 pm.serverPool.disconnect(entry) 227 } 228 return err 229 case <-pm.quitSync: 230 if entry != nil { 231 pm.serverPool.disconnect(entry) 232 } 233 return p2p.DiscQuitting 234 } 235 } 236 237 func (pm *ProtocolManager) newPeer(pv int, nv uint64, p *p2p.Peer, rw p2p.MsgReadWriter) *peer { 238 return newPeer(pv, nv, p, newMeteredMsgWriter(rw)) 239 } 240 241 // handle is the callback invoked to manage the life cycle of a les peer. When 242 // this function terminates, the peer is disconnected. 243 func (pm *ProtocolManager) handle(p *peer) error { 244 // Ignore maxPeers if this is a trusted peer 245 // In server mode we try to check into the client pool after handshake 246 if pm.lightSync && pm.peers.Len() >= pm.maxPeers && !p.Peer.Info().Network.Trusted { 247 return p2p.DiscTooManyPeers 248 } 249 250 p.Log().Debug("Light Ethereum peer connected", "name", p.Name()) 251 252 // Execute the LES handshake 253 var ( 254 genesis = pm.blockchain.Genesis() 255 head = pm.blockchain.CurrentHeader() 256 hash = head.Hash() 257 number = head.Number.Uint64() 258 td = pm.blockchain.GetTd(hash, number) 259 ) 260 if err := p.Handshake(td, hash, number, genesis.Hash(), pm.server); err != nil { 261 p.Log().Debug("Light Ethereum handshake failed", "err", err) 262 return err 263 } 264 265 if !pm.lightSync && !p.Peer.Info().Network.Trusted { 266 addr, ok := p.RemoteAddr().(*net.TCPAddr) 267 // test peer address is not a tcp address, don't use client pool if can not typecast 268 if ok { 269 id := addr.IP.String() 270 if !pm.clientPool.connect(id, func() { go pm.removePeer(p.id) }) { 271 return p2p.DiscTooManyPeers 272 } 273 defer pm.clientPool.disconnect(id) 274 } 275 } 276 277 if rw, ok := p.rw.(*meteredMsgReadWriter); ok { 278 rw.Init(p.version) 279 } 280 // Register the peer locally 281 if err := pm.peers.Register(p); err != nil { 282 p.Log().Error("Light Ethereum peer registration failed", "err", err) 283 return err 284 } 285 defer func() { 286 if pm.server != nil && pm.server.fcManager != nil && p.fcClient != nil { 287 p.fcClient.Remove(pm.server.fcManager) 288 } 289 pm.removePeer(p.id) 290 }() 291 // Register the peer in the downloader. If the downloader considers it banned, we disconnect 292 if pm.lightSync { 293 p.lock.Lock() 294 head := p.headInfo 295 p.lock.Unlock() 296 if pm.fetcher != nil { 297 pm.fetcher.announce(p, head) 298 } 299 300 if p.poolEntry != nil { 301 pm.serverPool.registered(p.poolEntry) 302 } 303 } 304 305 stop := make(chan struct{}) 306 defer close(stop) 307 go func() { 308 // new block announce loop 309 for { 310 select { 311 case announce := <-p.announceChn: 312 p.SendAnnounce(announce) 313 case <-stop: 314 return 315 } 316 } 317 }() 318 319 // main loop. handle incoming messages. 320 for { 321 if err := pm.handleMsg(p); err != nil { 322 p.Log().Debug("Light Ethereum message handling failed", "err", err) 323 return err 324 } 325 } 326 } 327 328 var reqList = []uint64{GetBlockHeadersMsg, GetBlockBodiesMsg, GetCodeMsg, GetReceiptsMsg, GetProofsV1Msg, SendTxMsg, SendTxV2Msg, GetTxStatusMsg, GetHeaderProofsMsg, GetProofsV2Msg, GetHelperTrieProofsMsg} 329 330 // handleMsg is invoked whenever an inbound message is received from a remote 331 // peer. The remote connection is torn down upon returning any error. 332 func (pm *ProtocolManager) handleMsg(p *peer) error { 333 // Read the next message from the remote peer, and ensure it's fully consumed 334 msg, err := p.rw.ReadMsg() 335 if err != nil { 336 return err 337 } 338 p.Log().Trace("Light Ethereum message arrived", "code", msg.Code, "bytes", msg.Size) 339 340 costs := p.fcCosts[msg.Code] 341 reject := func(reqCnt, maxCnt uint64) bool { 342 if p.fcClient == nil || reqCnt > maxCnt { 343 return true 344 } 345 bufValue, _ := p.fcClient.AcceptRequest() 346 cost := costs.baseCost + reqCnt*costs.reqCost 347 if cost > pm.server.defParams.BufLimit { 348 cost = pm.server.defParams.BufLimit 349 } 350 if cost > bufValue { 351 recharge := time.Duration((cost - bufValue) * 1000000 / pm.server.defParams.MinRecharge) 352 p.Log().Error("Request came too early", "recharge", common.PrettyDuration(recharge)) 353 return true 354 } 355 return false 356 } 357 358 if msg.Size > ProtocolMaxMsgSize { 359 return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize) 360 } 361 defer msg.Discard() 362 363 var deliverMsg *Msg 364 365 // Handle the message depending on its contents 366 switch msg.Code { 367 case StatusMsg: 368 p.Log().Trace("Received status message") 369 // Status messages should never arrive after the handshake 370 return errResp(ErrExtraStatusMsg, "uncontrolled status message") 371 372 // Block header query, collect the requested headers and reply 373 case AnnounceMsg: 374 p.Log().Trace("Received announce message") 375 if p.requestAnnounceType == announceTypeNone { 376 return errResp(ErrUnexpectedResponse, "") 377 } 378 379 var req announceData 380 if err := msg.Decode(&req); err != nil { 381 return errResp(ErrDecode, "%v: %v", msg, err) 382 } 383 384 if p.requestAnnounceType == announceTypeSigned { 385 if err := req.checkSignature(p.pubKey); err != nil { 386 p.Log().Trace("Invalid announcement signature", "err", err) 387 return err 388 } 389 p.Log().Trace("Valid announcement signature") 390 } 391 392 p.Log().Trace("Announce message content", "number", req.Number, "hash", req.Hash, "td", req.Td, "reorg", req.ReorgDepth) 393 if pm.fetcher != nil { 394 pm.fetcher.announce(p, &req) 395 } 396 397 case GetBlockHeadersMsg: 398 p.Log().Trace("Received block header request") 399 // Decode the complex header query 400 var req struct { 401 ReqID uint64 402 Query getBlockHeadersData 403 } 404 if err := msg.Decode(&req); err != nil { 405 return errResp(ErrDecode, "%v: %v", msg, err) 406 } 407 408 query := req.Query 409 if reject(query.Amount, MaxHeaderFetch) { 410 return errResp(ErrRequestRejected, "") 411 } 412 413 hashMode := query.Origin.Hash != (common.Hash{}) 414 first := true 415 maxNonCanonical := uint64(100) 416 417 // Gather headers until the fetch or network limits is reached 418 var ( 419 bytes common.StorageSize 420 headers []*types.Header 421 unknown bool 422 ) 423 for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit { 424 // Retrieve the next header satisfying the query 425 var origin *types.Header 426 if hashMode { 427 if first { 428 first = false 429 origin = pm.blockchain.GetHeaderByHash(query.Origin.Hash) 430 if origin != nil { 431 query.Origin.Number = origin.Number.Uint64() 432 } 433 } else { 434 origin = pm.blockchain.GetHeader(query.Origin.Hash, query.Origin.Number) 435 } 436 } else { 437 origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number) 438 } 439 if origin == nil { 440 break 441 } 442 headers = append(headers, origin) 443 bytes += estHeaderRlpSize 444 445 // Advance to the next header of the query 446 switch { 447 case hashMode && query.Reverse: 448 // Hash based traversal towards the genesis block 449 ancestor := query.Skip + 1 450 if ancestor == 0 { 451 unknown = true 452 } else { 453 query.Origin.Hash, query.Origin.Number = pm.blockchain.GetAncestor(query.Origin.Hash, query.Origin.Number, ancestor, &maxNonCanonical) 454 unknown = (query.Origin.Hash == common.Hash{}) 455 } 456 case hashMode && !query.Reverse: 457 // Hash based traversal towards the leaf block 458 var ( 459 current = origin.Number.Uint64() 460 next = current + query.Skip + 1 461 ) 462 if next <= current { 463 infos, _ := json.MarshalIndent(p.Peer.Info(), "", " ") 464 p.Log().Warn("GetBlockHeaders skip overflow attack", "current", current, "skip", query.Skip, "next", next, "attacker", infos) 465 unknown = true 466 } else { 467 if header := pm.blockchain.GetHeaderByNumber(next); header != nil { 468 nextHash := header.Hash() 469 expOldHash, _ := pm.blockchain.GetAncestor(nextHash, next, query.Skip+1, &maxNonCanonical) 470 if expOldHash == query.Origin.Hash { 471 query.Origin.Hash, query.Origin.Number = nextHash, next 472 } else { 473 unknown = true 474 } 475 } else { 476 unknown = true 477 } 478 } 479 case query.Reverse: 480 // Number based traversal towards the genesis block 481 if query.Origin.Number >= query.Skip+1 { 482 query.Origin.Number -= query.Skip + 1 483 } else { 484 unknown = true 485 } 486 487 case !query.Reverse: 488 // Number based traversal towards the leaf block 489 query.Origin.Number += query.Skip + 1 490 } 491 } 492 493 bv, rcost := p.fcClient.RequestProcessed(costs.baseCost + query.Amount*costs.reqCost) 494 pm.server.fcCostStats.update(msg.Code, query.Amount, rcost) 495 return p.SendBlockHeaders(req.ReqID, bv, headers) 496 497 case BlockHeadersMsg: 498 if pm.downloader == nil { 499 return errResp(ErrUnexpectedResponse, "") 500 } 501 502 p.Log().Trace("Received block header response message") 503 // A batch of headers arrived to one of our previous requests 504 var resp struct { 505 ReqID, BV uint64 506 Headers []*types.Header 507 } 508 if err := msg.Decode(&resp); err != nil { 509 return errResp(ErrDecode, "msg %v: %v", msg, err) 510 } 511 p.fcServer.GotReply(resp.ReqID, resp.BV) 512 if pm.fetcher != nil && pm.fetcher.requestedID(resp.ReqID) { 513 pm.fetcher.deliverHeaders(p, resp.ReqID, resp.Headers) 514 } else { 515 err := pm.downloader.DeliverHeaders(p.id, resp.Headers) 516 if err != nil { 517 log.Debug(fmt.Sprint(err)) 518 } 519 } 520 521 case GetBlockBodiesMsg: 522 p.Log().Trace("Received block bodies request") 523 // Decode the retrieval message 524 var req struct { 525 ReqID uint64 526 Hashes []common.Hash 527 } 528 if err := msg.Decode(&req); err != nil { 529 return errResp(ErrDecode, "msg %v: %v", msg, err) 530 } 531 // Gather blocks until the fetch or network limits is reached 532 var ( 533 bytes int 534 bodies []rlp.RawValue 535 ) 536 reqCnt := len(req.Hashes) 537 if reject(uint64(reqCnt), MaxBodyFetch) { 538 return errResp(ErrRequestRejected, "") 539 } 540 for _, hash := range req.Hashes { 541 if bytes >= softResponseLimit { 542 break 543 } 544 // Retrieve the requested block body, stopping if enough was found 545 if number := rawdb.ReadHeaderNumber(pm.chainDb, hash); number != nil { 546 if data := rawdb.ReadBodyRLP(pm.chainDb, hash, *number); len(data) != 0 { 547 bodies = append(bodies, data) 548 bytes += len(data) 549 } 550 } 551 } 552 bv, rcost := p.fcClient.RequestProcessed(costs.baseCost + uint64(reqCnt)*costs.reqCost) 553 pm.server.fcCostStats.update(msg.Code, uint64(reqCnt), rcost) 554 return p.SendBlockBodiesRLP(req.ReqID, bv, bodies) 555 556 case BlockBodiesMsg: 557 if pm.odr == nil { 558 return errResp(ErrUnexpectedResponse, "") 559 } 560 561 p.Log().Trace("Received block bodies response") 562 // A batch of block bodies arrived to one of our previous requests 563 var resp struct { 564 ReqID, BV uint64 565 Data []*types.Body 566 } 567 if err := msg.Decode(&resp); err != nil { 568 return errResp(ErrDecode, "msg %v: %v", msg, err) 569 } 570 p.fcServer.GotReply(resp.ReqID, resp.BV) 571 deliverMsg = &Msg{ 572 MsgType: MsgBlockBodies, 573 ReqID: resp.ReqID, 574 Obj: resp.Data, 575 } 576 577 case GetCodeMsg: 578 p.Log().Trace("Received code request") 579 // Decode the retrieval message 580 var req struct { 581 ReqID uint64 582 Reqs []CodeReq 583 } 584 if err := msg.Decode(&req); err != nil { 585 return errResp(ErrDecode, "msg %v: %v", msg, err) 586 } 587 // Gather state data until the fetch or network limits is reached 588 var ( 589 bytes int 590 data [][]byte 591 ) 592 reqCnt := len(req.Reqs) 593 if reject(uint64(reqCnt), MaxCodeFetch) { 594 return errResp(ErrRequestRejected, "") 595 } 596 for _, req := range req.Reqs { 597 // Retrieve the requested state entry, stopping if enough was found 598 if number := rawdb.ReadHeaderNumber(pm.chainDb, req.BHash); number != nil { 599 if header := rawdb.ReadHeader(pm.chainDb, req.BHash, *number); header != nil { 600 statedb, err := pm.blockchain.State() 601 if err != nil { 602 continue 603 } 604 account, err := pm.getAccount(statedb, header.Root, common.BytesToHash(req.AccKey)) 605 if err != nil { 606 continue 607 } 608 code, _ := statedb.Database().TrieDB().Node(common.BytesToHash(account.CodeHash)) 609 610 data = append(data, code) 611 if bytes += len(code); bytes >= softResponseLimit { 612 break 613 } 614 } 615 } 616 } 617 bv, rcost := p.fcClient.RequestProcessed(costs.baseCost + uint64(reqCnt)*costs.reqCost) 618 pm.server.fcCostStats.update(msg.Code, uint64(reqCnt), rcost) 619 return p.SendCode(req.ReqID, bv, data) 620 621 case CodeMsg: 622 if pm.odr == nil { 623 return errResp(ErrUnexpectedResponse, "") 624 } 625 626 p.Log().Trace("Received code response") 627 // A batch of node state data arrived to one of our previous requests 628 var resp struct { 629 ReqID, BV uint64 630 Data [][]byte 631 } 632 if err := msg.Decode(&resp); err != nil { 633 return errResp(ErrDecode, "msg %v: %v", msg, err) 634 } 635 p.fcServer.GotReply(resp.ReqID, resp.BV) 636 deliverMsg = &Msg{ 637 MsgType: MsgCode, 638 ReqID: resp.ReqID, 639 Obj: resp.Data, 640 } 641 642 case GetReceiptsMsg: 643 p.Log().Trace("Received receipts request") 644 // Decode the retrieval message 645 var req struct { 646 ReqID uint64 647 Hashes []common.Hash 648 } 649 if err := msg.Decode(&req); err != nil { 650 return errResp(ErrDecode, "msg %v: %v", msg, err) 651 } 652 // Gather state data until the fetch or network limits is reached 653 var ( 654 bytes int 655 receipts []rlp.RawValue 656 ) 657 reqCnt := len(req.Hashes) 658 if reject(uint64(reqCnt), MaxReceiptFetch) { 659 return errResp(ErrRequestRejected, "") 660 } 661 for _, hash := range req.Hashes { 662 if bytes >= softResponseLimit { 663 break 664 } 665 // Retrieve the requested block's receipts, skipping if unknown to us 666 var results types.Receipts 667 if number := rawdb.ReadHeaderNumber(pm.chainDb, hash); number != nil { 668 results = rawdb.ReadReceipts(pm.chainDb, hash, *number) 669 } 670 if results == nil { 671 if header := pm.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash { 672 continue 673 } 674 } 675 // If known, encode and queue for response packet 676 if encoded, err := rlp.EncodeToBytes(results); err != nil { 677 log.Error("Failed to encode receipt", "err", err) 678 } else { 679 receipts = append(receipts, encoded) 680 bytes += len(encoded) 681 } 682 } 683 bv, rcost := p.fcClient.RequestProcessed(costs.baseCost + uint64(reqCnt)*costs.reqCost) 684 pm.server.fcCostStats.update(msg.Code, uint64(reqCnt), rcost) 685 return p.SendReceiptsRLP(req.ReqID, bv, receipts) 686 687 case ReceiptsMsg: 688 if pm.odr == nil { 689 return errResp(ErrUnexpectedResponse, "") 690 } 691 692 p.Log().Trace("Received receipts response") 693 // A batch of receipts arrived to one of our previous requests 694 var resp struct { 695 ReqID, BV uint64 696 Receipts []types.Receipts 697 } 698 if err := msg.Decode(&resp); err != nil { 699 return errResp(ErrDecode, "msg %v: %v", msg, err) 700 } 701 p.fcServer.GotReply(resp.ReqID, resp.BV) 702 deliverMsg = &Msg{ 703 MsgType: MsgReceipts, 704 ReqID: resp.ReqID, 705 Obj: resp.Receipts, 706 } 707 708 case GetProofsV1Msg: 709 p.Log().Trace("Received proofs request") 710 // Decode the retrieval message 711 var req struct { 712 ReqID uint64 713 Reqs []ProofReq 714 } 715 if err := msg.Decode(&req); err != nil { 716 return errResp(ErrDecode, "msg %v: %v", msg, err) 717 } 718 // Gather state data until the fetch or network limits is reached 719 var ( 720 bytes int 721 proofs proofsData 722 ) 723 reqCnt := len(req.Reqs) 724 if reject(uint64(reqCnt), MaxProofsFetch) { 725 return errResp(ErrRequestRejected, "") 726 } 727 for _, req := range req.Reqs { 728 // Retrieve the requested state entry, stopping if enough was found 729 if number := rawdb.ReadHeaderNumber(pm.chainDb, req.BHash); number != nil { 730 if header := rawdb.ReadHeader(pm.chainDb, req.BHash, *number); header != nil { 731 statedb, err := pm.blockchain.State() 732 if err != nil { 733 continue 734 } 735 var trie state.Trie 736 if len(req.AccKey) > 0 { 737 account, err := pm.getAccount(statedb, header.Root, common.BytesToHash(req.AccKey)) 738 if err != nil { 739 continue 740 } 741 trie, _ = statedb.Database().OpenStorageTrie(common.BytesToHash(req.AccKey), account.Root) 742 } else { 743 trie, _ = statedb.Database().OpenTrie(header.Root) 744 } 745 if trie != nil { 746 var proof light.NodeList 747 trie.Prove(req.Key, 0, &proof) 748 749 proofs = append(proofs, proof) 750 if bytes += proof.DataSize(); bytes >= softResponseLimit { 751 break 752 } 753 } 754 } 755 } 756 } 757 bv, rcost := p.fcClient.RequestProcessed(costs.baseCost + uint64(reqCnt)*costs.reqCost) 758 pm.server.fcCostStats.update(msg.Code, uint64(reqCnt), rcost) 759 return p.SendProofs(req.ReqID, bv, proofs) 760 761 case GetProofsV2Msg: 762 p.Log().Trace("Received les/2 proofs request") 763 // Decode the retrieval message 764 var req struct { 765 ReqID uint64 766 Reqs []ProofReq 767 } 768 if err := msg.Decode(&req); err != nil { 769 return errResp(ErrDecode, "msg %v: %v", msg, err) 770 } 771 // Gather state data until the fetch or network limits is reached 772 var ( 773 lastBHash common.Hash 774 statedb *state.StateDB 775 root common.Hash 776 ) 777 reqCnt := len(req.Reqs) 778 if reject(uint64(reqCnt), MaxProofsFetch) { 779 return errResp(ErrRequestRejected, "") 780 } 781 782 nodes := light.NewNodeSet() 783 784 for _, req := range req.Reqs { 785 // Look up the state belonging to the request 786 if statedb == nil || req.BHash != lastBHash { 787 statedb, root, lastBHash = nil, common.Hash{}, req.BHash 788 789 if number := rawdb.ReadHeaderNumber(pm.chainDb, req.BHash); number != nil { 790 if header := rawdb.ReadHeader(pm.chainDb, req.BHash, *number); header != nil { 791 statedb, _ = pm.blockchain.State() 792 root = header.Root 793 } 794 } 795 } 796 if statedb == nil { 797 continue 798 } 799 // Pull the account or storage trie of the request 800 var trie state.Trie 801 if len(req.AccKey) > 0 { 802 account, err := pm.getAccount(statedb, root, common.BytesToHash(req.AccKey)) 803 if err != nil { 804 continue 805 } 806 trie, _ = statedb.Database().OpenStorageTrie(common.BytesToHash(req.AccKey), account.Root) 807 } else { 808 trie, _ = statedb.Database().OpenTrie(root) 809 } 810 if trie == nil { 811 continue 812 } 813 // Prove the user's request from the account or stroage trie 814 trie.Prove(req.Key, req.FromLevel, nodes) 815 if nodes.DataSize() >= softResponseLimit { 816 break 817 } 818 } 819 bv, rcost := p.fcClient.RequestProcessed(costs.baseCost + uint64(reqCnt)*costs.reqCost) 820 pm.server.fcCostStats.update(msg.Code, uint64(reqCnt), rcost) 821 return p.SendProofsV2(req.ReqID, bv, nodes.NodeList()) 822 823 case ProofsV1Msg: 824 if pm.odr == nil { 825 return errResp(ErrUnexpectedResponse, "") 826 } 827 828 p.Log().Trace("Received proofs response") 829 // A batch of merkle proofs arrived to one of our previous requests 830 var resp struct { 831 ReqID, BV uint64 832 Data []light.NodeList 833 } 834 if err := msg.Decode(&resp); err != nil { 835 return errResp(ErrDecode, "msg %v: %v", msg, err) 836 } 837 p.fcServer.GotReply(resp.ReqID, resp.BV) 838 deliverMsg = &Msg{ 839 MsgType: MsgProofsV1, 840 ReqID: resp.ReqID, 841 Obj: resp.Data, 842 } 843 844 case ProofsV2Msg: 845 if pm.odr == nil { 846 return errResp(ErrUnexpectedResponse, "") 847 } 848 849 p.Log().Trace("Received les/2 proofs response") 850 // A batch of merkle proofs arrived to one of our previous requests 851 var resp struct { 852 ReqID, BV uint64 853 Data light.NodeList 854 } 855 if err := msg.Decode(&resp); err != nil { 856 return errResp(ErrDecode, "msg %v: %v", msg, err) 857 } 858 p.fcServer.GotReply(resp.ReqID, resp.BV) 859 deliverMsg = &Msg{ 860 MsgType: MsgProofsV2, 861 ReqID: resp.ReqID, 862 Obj: resp.Data, 863 } 864 865 case GetHeaderProofsMsg: 866 p.Log().Trace("Received headers proof request") 867 // Decode the retrieval message 868 var req struct { 869 ReqID uint64 870 Reqs []ChtReq 871 } 872 if err := msg.Decode(&req); err != nil { 873 return errResp(ErrDecode, "msg %v: %v", msg, err) 874 } 875 // Gather state data until the fetch or network limits is reached 876 var ( 877 bytes int 878 proofs []ChtResp 879 ) 880 reqCnt := len(req.Reqs) 881 if reject(uint64(reqCnt), MaxHelperTrieProofsFetch) { 882 return errResp(ErrRequestRejected, "") 883 } 884 trieDb := trie.NewDatabase(ethdb.NewTable(pm.chainDb, light.ChtTablePrefix)) 885 for _, req := range req.Reqs { 886 if header := pm.blockchain.GetHeaderByNumber(req.BlockNum); header != nil { 887 sectionHead := rawdb.ReadCanonicalHash(pm.chainDb, req.ChtNum*pm.iConfig.ChtSize-1) 888 if root := light.GetChtRoot(pm.chainDb, req.ChtNum-1, sectionHead); root != (common.Hash{}) { 889 trie, err := trie.New(root, trieDb) 890 if err != nil { 891 continue 892 } 893 var encNumber [8]byte 894 binary.BigEndian.PutUint64(encNumber[:], req.BlockNum) 895 896 var proof light.NodeList 897 trie.Prove(encNumber[:], 0, &proof) 898 899 proofs = append(proofs, ChtResp{Header: header, Proof: proof}) 900 if bytes += proof.DataSize() + estHeaderRlpSize; bytes >= softResponseLimit { 901 break 902 } 903 } 904 } 905 } 906 bv, rcost := p.fcClient.RequestProcessed(costs.baseCost + uint64(reqCnt)*costs.reqCost) 907 pm.server.fcCostStats.update(msg.Code, uint64(reqCnt), rcost) 908 return p.SendHeaderProofs(req.ReqID, bv, proofs) 909 910 case GetHelperTrieProofsMsg: 911 p.Log().Trace("Received helper trie proof request") 912 // Decode the retrieval message 913 var req struct { 914 ReqID uint64 915 Reqs []HelperTrieReq 916 } 917 if err := msg.Decode(&req); err != nil { 918 return errResp(ErrDecode, "msg %v: %v", msg, err) 919 } 920 // Gather state data until the fetch or network limits is reached 921 var ( 922 auxBytes int 923 auxData [][]byte 924 ) 925 reqCnt := len(req.Reqs) 926 if reject(uint64(reqCnt), MaxHelperTrieProofsFetch) { 927 return errResp(ErrRequestRejected, "") 928 } 929 930 var ( 931 lastIdx uint64 932 lastType uint 933 root common.Hash 934 auxTrie *trie.Trie 935 ) 936 nodes := light.NewNodeSet() 937 for _, req := range req.Reqs { 938 if auxTrie == nil || req.Type != lastType || req.TrieIdx != lastIdx { 939 auxTrie, lastType, lastIdx = nil, req.Type, req.TrieIdx 940 941 var prefix string 942 if root, prefix = pm.getHelperTrie(req.Type, req.TrieIdx); root != (common.Hash{}) { 943 auxTrie, _ = trie.New(root, trie.NewDatabase(ethdb.NewTable(pm.chainDb, prefix))) 944 } 945 } 946 if req.AuxReq == auxRoot { 947 var data []byte 948 if root != (common.Hash{}) { 949 data = root[:] 950 } 951 auxData = append(auxData, data) 952 auxBytes += len(data) 953 } else { 954 if auxTrie != nil { 955 auxTrie.Prove(req.Key, req.FromLevel, nodes) 956 } 957 if req.AuxReq != 0 { 958 data := pm.getHelperTrieAuxData(req) 959 auxData = append(auxData, data) 960 auxBytes += len(data) 961 } 962 } 963 if nodes.DataSize()+auxBytes >= softResponseLimit { 964 break 965 } 966 } 967 bv, rcost := p.fcClient.RequestProcessed(costs.baseCost + uint64(reqCnt)*costs.reqCost) 968 pm.server.fcCostStats.update(msg.Code, uint64(reqCnt), rcost) 969 return p.SendHelperTrieProofs(req.ReqID, bv, HelperTrieResps{Proofs: nodes.NodeList(), AuxData: auxData}) 970 971 case HeaderProofsMsg: 972 if pm.odr == nil { 973 return errResp(ErrUnexpectedResponse, "") 974 } 975 976 p.Log().Trace("Received headers proof response") 977 var resp struct { 978 ReqID, BV uint64 979 Data []ChtResp 980 } 981 if err := msg.Decode(&resp); err != nil { 982 return errResp(ErrDecode, "msg %v: %v", msg, err) 983 } 984 p.fcServer.GotReply(resp.ReqID, resp.BV) 985 deliverMsg = &Msg{ 986 MsgType: MsgHeaderProofs, 987 ReqID: resp.ReqID, 988 Obj: resp.Data, 989 } 990 991 case HelperTrieProofsMsg: 992 if pm.odr == nil { 993 return errResp(ErrUnexpectedResponse, "") 994 } 995 996 p.Log().Trace("Received helper trie proof response") 997 var resp struct { 998 ReqID, BV uint64 999 Data HelperTrieResps 1000 } 1001 if err := msg.Decode(&resp); err != nil { 1002 return errResp(ErrDecode, "msg %v: %v", msg, err) 1003 } 1004 1005 p.fcServer.GotReply(resp.ReqID, resp.BV) 1006 deliverMsg = &Msg{ 1007 MsgType: MsgHelperTrieProofs, 1008 ReqID: resp.ReqID, 1009 Obj: resp.Data, 1010 } 1011 1012 case SendTxMsg: 1013 if pm.txpool == nil { 1014 return errResp(ErrRequestRejected, "") 1015 } 1016 // Transactions arrived, parse all of them and deliver to the pool 1017 var txs []*types.Transaction 1018 if err := msg.Decode(&txs); err != nil { 1019 return errResp(ErrDecode, "msg %v: %v", msg, err) 1020 } 1021 reqCnt := len(txs) 1022 if reject(uint64(reqCnt), MaxTxSend) { 1023 return errResp(ErrRequestRejected, "") 1024 } 1025 pm.txpool.AddRemotes(txs) 1026 1027 _, rcost := p.fcClient.RequestProcessed(costs.baseCost + uint64(reqCnt)*costs.reqCost) 1028 pm.server.fcCostStats.update(msg.Code, uint64(reqCnt), rcost) 1029 1030 case SendTxV2Msg: 1031 if pm.txpool == nil { 1032 return errResp(ErrRequestRejected, "") 1033 } 1034 // Transactions arrived, parse all of them and deliver to the pool 1035 var req struct { 1036 ReqID uint64 1037 Txs []*types.Transaction 1038 } 1039 if err := msg.Decode(&req); err != nil { 1040 return errResp(ErrDecode, "msg %v: %v", msg, err) 1041 } 1042 reqCnt := len(req.Txs) 1043 if reject(uint64(reqCnt), MaxTxSend) { 1044 return errResp(ErrRequestRejected, "") 1045 } 1046 1047 hashes := make([]common.Hash, len(req.Txs)) 1048 for i, tx := range req.Txs { 1049 hashes[i] = tx.Hash() 1050 } 1051 stats := pm.txStatus(hashes) 1052 for i, stat := range stats { 1053 if stat.Status == core.TxStatusUnknown { 1054 if errs := pm.txpool.AddRemotes([]*types.Transaction{req.Txs[i]}); errs[0] != nil { 1055 stats[i].Error = errs[0].Error() 1056 continue 1057 } 1058 stats[i] = pm.txStatus([]common.Hash{hashes[i]})[0] 1059 } 1060 } 1061 1062 bv, rcost := p.fcClient.RequestProcessed(costs.baseCost + uint64(reqCnt)*costs.reqCost) 1063 pm.server.fcCostStats.update(msg.Code, uint64(reqCnt), rcost) 1064 1065 return p.SendTxStatus(req.ReqID, bv, stats) 1066 1067 case GetTxStatusMsg: 1068 if pm.txpool == nil { 1069 return errResp(ErrUnexpectedResponse, "") 1070 } 1071 // Transactions arrived, parse all of them and deliver to the pool 1072 var req struct { 1073 ReqID uint64 1074 Hashes []common.Hash 1075 } 1076 if err := msg.Decode(&req); err != nil { 1077 return errResp(ErrDecode, "msg %v: %v", msg, err) 1078 } 1079 reqCnt := len(req.Hashes) 1080 if reject(uint64(reqCnt), MaxTxStatus) { 1081 return errResp(ErrRequestRejected, "") 1082 } 1083 bv, rcost := p.fcClient.RequestProcessed(costs.baseCost + uint64(reqCnt)*costs.reqCost) 1084 pm.server.fcCostStats.update(msg.Code, uint64(reqCnt), rcost) 1085 1086 return p.SendTxStatus(req.ReqID, bv, pm.txStatus(req.Hashes)) 1087 1088 case TxStatusMsg: 1089 if pm.odr == nil { 1090 return errResp(ErrUnexpectedResponse, "") 1091 } 1092 1093 p.Log().Trace("Received tx status response") 1094 var resp struct { 1095 ReqID, BV uint64 1096 Status []txStatus 1097 } 1098 if err := msg.Decode(&resp); err != nil { 1099 return errResp(ErrDecode, "msg %v: %v", msg, err) 1100 } 1101 1102 p.fcServer.GotReply(resp.ReqID, resp.BV) 1103 1104 default: 1105 p.Log().Trace("Received unknown message", "code", msg.Code) 1106 return errResp(ErrInvalidMsgCode, "%v", msg.Code) 1107 } 1108 1109 if deliverMsg != nil { 1110 err := pm.retriever.deliver(p, deliverMsg) 1111 if err != nil { 1112 p.responseErrors++ 1113 if p.responseErrors > maxResponseErrors { 1114 return err 1115 } 1116 } 1117 } 1118 return nil 1119 } 1120 1121 // getAccount retrieves an account from the state based at root. 1122 func (pm *ProtocolManager) getAccount(statedb *state.StateDB, root, hash common.Hash) (state.Account, error) { 1123 trie, err := trie.New(root, statedb.Database().TrieDB()) 1124 if err != nil { 1125 return state.Account{}, err 1126 } 1127 blob, err := trie.TryGet(hash[:]) 1128 if err != nil { 1129 return state.Account{}, err 1130 } 1131 var account state.Account 1132 if err = rlp.DecodeBytes(blob, &account); err != nil { 1133 return state.Account{}, err 1134 } 1135 return account, nil 1136 } 1137 1138 // getHelperTrie returns the post-processed trie root for the given trie ID and section index 1139 func (pm *ProtocolManager) getHelperTrie(id uint, idx uint64) (common.Hash, string) { 1140 switch id { 1141 case htCanonical: 1142 idxV1 := (idx+1)*(pm.iConfig.PairChtSize/pm.iConfig.ChtSize) - 1 1143 sectionHead := rawdb.ReadCanonicalHash(pm.chainDb, (idxV1+1)*pm.iConfig.ChtSize-1) 1144 return light.GetChtRoot(pm.chainDb, idxV1, sectionHead), light.ChtTablePrefix 1145 case htBloomBits: 1146 sectionHead := rawdb.ReadCanonicalHash(pm.chainDb, (idx+1)*pm.iConfig.BloomTrieSize-1) 1147 return light.GetBloomTrieRoot(pm.chainDb, idx, sectionHead), light.BloomTrieTablePrefix 1148 } 1149 return common.Hash{}, "" 1150 } 1151 1152 // getHelperTrieAuxData returns requested auxiliary data for the given HelperTrie request 1153 func (pm *ProtocolManager) getHelperTrieAuxData(req HelperTrieReq) []byte { 1154 if req.Type == htCanonical && req.AuxReq == auxHeader && len(req.Key) == 8 { 1155 blockNum := binary.BigEndian.Uint64(req.Key) 1156 hash := rawdb.ReadCanonicalHash(pm.chainDb, blockNum) 1157 return rawdb.ReadHeaderRLP(pm.chainDb, hash, blockNum) 1158 } 1159 return nil 1160 } 1161 1162 func (pm *ProtocolManager) txStatus(hashes []common.Hash) []txStatus { 1163 stats := make([]txStatus, len(hashes)) 1164 for i, stat := range pm.txpool.Status(hashes) { 1165 // Save the status we've got from the transaction pool 1166 stats[i].Status = stat 1167 1168 // If the transaction is unknown to the pool, try looking it up locally 1169 if stat == core.TxStatusUnknown { 1170 if block, number, index := rawdb.ReadTxLookupEntry(pm.chainDb, hashes[i]); block != (common.Hash{}) { 1171 stats[i].Status = core.TxStatusIncluded 1172 stats[i].Lookup = &rawdb.TxLookupEntry{BlockHash: block, BlockIndex: number, Index: index} 1173 } 1174 } 1175 } 1176 return stats 1177 } 1178 1179 // downloaderPeerNotify implements peerSetNotify 1180 type downloaderPeerNotify ProtocolManager 1181 1182 type peerConnection struct { 1183 manager *ProtocolManager 1184 peer *peer 1185 } 1186 1187 func (pc *peerConnection) Head() (common.Hash, *big.Int) { 1188 return pc.peer.HeadAndTd() 1189 } 1190 1191 func (pc *peerConnection) RequestHeadersByHash(origin common.Hash, amount int, skip int, reverse bool) error { 1192 reqID := genReqID() 1193 rq := &distReq{ 1194 getCost: func(dp distPeer) uint64 { 1195 peer := dp.(*peer) 1196 return peer.GetRequestCost(GetBlockHeadersMsg, amount) 1197 }, 1198 canSend: func(dp distPeer) bool { 1199 return dp.(*peer) == pc.peer 1200 }, 1201 request: func(dp distPeer) func() { 1202 peer := dp.(*peer) 1203 cost := peer.GetRequestCost(GetBlockHeadersMsg, amount) 1204 peer.fcServer.QueueRequest(reqID, cost) 1205 return func() { peer.RequestHeadersByHash(reqID, cost, origin, amount, skip, reverse) } 1206 }, 1207 } 1208 _, ok := <-pc.manager.reqDist.queue(rq) 1209 if !ok { 1210 return light.ErrNoPeers 1211 } 1212 return nil 1213 } 1214 1215 func (pc *peerConnection) RequestHeadersByNumber(origin uint64, amount int, skip int, reverse bool) error { 1216 reqID := genReqID() 1217 rq := &distReq{ 1218 getCost: func(dp distPeer) uint64 { 1219 peer := dp.(*peer) 1220 return peer.GetRequestCost(GetBlockHeadersMsg, amount) 1221 }, 1222 canSend: func(dp distPeer) bool { 1223 return dp.(*peer) == pc.peer 1224 }, 1225 request: func(dp distPeer) func() { 1226 peer := dp.(*peer) 1227 cost := peer.GetRequestCost(GetBlockHeadersMsg, amount) 1228 peer.fcServer.QueueRequest(reqID, cost) 1229 return func() { peer.RequestHeadersByNumber(reqID, cost, origin, amount, skip, reverse) } 1230 }, 1231 } 1232 _, ok := <-pc.manager.reqDist.queue(rq) 1233 if !ok { 1234 return light.ErrNoPeers 1235 } 1236 return nil 1237 } 1238 1239 func (d *downloaderPeerNotify) registerPeer(p *peer) { 1240 pm := (*ProtocolManager)(d) 1241 pc := &peerConnection{ 1242 manager: pm, 1243 peer: p, 1244 } 1245 pm.downloader.RegisterLightPeer(p.id, ethVersion, pc) 1246 } 1247 1248 func (d *downloaderPeerNotify) unregisterPeer(p *peer) { 1249 pm := (*ProtocolManager)(d) 1250 pm.downloader.UnregisterPeer(p.id) 1251 }