github.com/luckypickle/go-ethereum-vet@v1.14.2/les/sync.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 18 19 import ( 20 "context" 21 "time" 22 23 "github.com/luckypickle/go-ethereum-vet/core/rawdb" 24 "github.com/luckypickle/go-ethereum-vet/eth/downloader" 25 "github.com/luckypickle/go-ethereum-vet/light" 26 ) 27 28 // syncer is responsible for periodically synchronising with the network, both 29 // downloading hashes and blocks as well as handling the announcement handler. 30 func (pm *ProtocolManager) syncer() { 31 // Start and ensure cleanup of sync mechanisms 32 //pm.fetcher.Start() 33 //defer pm.fetcher.Stop() 34 defer pm.downloader.Terminate() 35 36 // Wait for different events to fire synchronisation operations 37 //forceSync := time.Tick(forceSyncCycle) 38 for { 39 select { 40 case <-pm.newPeerCh: 41 /* // Make sure we have peers to select from, then sync 42 if pm.peers.Len() < minDesiredPeerCount { 43 break 44 } 45 go pm.synchronise(pm.peers.BestPeer()) 46 */ 47 /*case <-forceSync: 48 // Force a sync even if not enough peers are present 49 go pm.synchronise(pm.peers.BestPeer()) 50 */ 51 case <-pm.noMorePeers: 52 return 53 } 54 } 55 } 56 57 func (pm *ProtocolManager) needToSync(peerHead blockInfo) bool { 58 head := pm.blockchain.CurrentHeader() 59 currentTd := rawdb.ReadTd(pm.chainDb, head.Hash(), head.Number.Uint64()) 60 return currentTd != nil && peerHead.Td.Cmp(currentTd) > 0 61 } 62 63 // synchronise tries to sync up our local block chain with a remote peer. 64 func (pm *ProtocolManager) synchronise(peer *peer) { 65 // Short circuit if no peers are available 66 if peer == nil { 67 return 68 } 69 70 // Make sure the peer's TD is higher than our own. 71 if !pm.needToSync(peer.headBlockInfo()) { 72 return 73 } 74 75 ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) 76 defer cancel() 77 pm.blockchain.(*light.LightChain).SyncCht(ctx) 78 pm.downloader.Synchronise(peer.id, peer.Head(), peer.Td(), downloader.LightSync) 79 }