github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/eth/downloader/fetchers.go (about) 1 // Copyright 2021 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 downloader 18 19 import ( 20 "time" 21 22 "github.com/ethereum/go-ethereum/common" 23 "github.com/ethereum/go-ethereum/core/types" 24 "github.com/ethereum/go-ethereum/eth/protocols/eth" 25 ) 26 27 // fetchHeadersByHash is a blocking version of Peer.RequestHeadersByHash which 28 // handles all the cancellation, interruption and timeout mechanisms of a data 29 // retrieval to allow blocking API calls. 30 func (d *Downloader) fetchHeadersByHash(p *peerConnection, hash common.Hash, amount int, skip int, reverse bool) ([]*types.Header, []common.Hash, error) { 31 // Create the response sink and send the network request 32 start := time.Now() 33 resCh := make(chan *eth.Response) 34 35 req, err := p.peer.RequestHeadersByHash(hash, amount, skip, reverse, resCh) 36 if err != nil { 37 return nil, nil, err 38 } 39 defer req.Close() 40 41 // Wait until the response arrives, the request is cancelled or times out 42 ttl := d.peers.rates.TargetTimeout() 43 44 timeoutTimer := time.NewTimer(ttl) 45 defer timeoutTimer.Stop() 46 47 select { 48 case <-d.cancelCh: 49 return nil, nil, errCanceled 50 51 case <-timeoutTimer.C: 52 // Header retrieval timed out, update the metrics 53 p.log.Debug("Header request timed out", "elapsed", ttl) 54 headerTimeoutMeter.Mark(1) 55 56 return nil, nil, errTimeout 57 58 case res := <-resCh: 59 // Headers successfully retrieved, update the metrics 60 headerReqTimer.Update(time.Since(start)) 61 headerInMeter.Mark(int64(len(*res.Res.(*eth.BlockHeadersRequest)))) 62 63 // Don't reject the packet even if it turns out to be bad, downloader will 64 // disconnect the peer on its own terms. Simply delivery the headers to 65 // be processed by the caller 66 res.Done <- nil 67 68 return *res.Res.(*eth.BlockHeadersRequest), res.Meta.([]common.Hash), nil 69 } 70 }