github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/les/sync.go (about) 1 // This file is part of the go-sberex library. The go-sberex library is 2 // free software: you can redistribute it and/or modify it under the terms 3 // of the GNU Lesser General Public License as published by the Free 4 // Software Foundation, either version 3 of the License, or (at your option) 5 // any later version. 6 // 7 // The go-sberex library is distributed in the hope that it will be useful, 8 // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 10 // General Public License <http://www.gnu.org/licenses/> for more details. 11 12 package les 13 14 import ( 15 "context" 16 "time" 17 18 "github.com/Sberex/go-sberex/core" 19 "github.com/Sberex/go-sberex/eth/downloader" 20 "github.com/Sberex/go-sberex/light" 21 ) 22 23 const ( 24 //forceSyncCycle = 10 * time.Second // Time interval to force syncs, even if few peers are available 25 minDesiredPeerCount = 5 // Amount of peers desired to start syncing 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 := core.GetTd(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 }