github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/les/sync.go (about) 1 package les 2 3 import ( 4 "context" 5 "time" 6 7 "github.com/quickchainproject/quickchain/core" 8 "github.com/quickchainproject/quickchain/qct/downloader" 9 "github.com/quickchainproject/quickchain/light" 10 ) 11 12 // syncer is responsible for periodically synchronising with the network, both 13 // downloading hashes and blocks as well as handling the announcement handler. 14 func (pm *ProtocolManager) syncer() { 15 // Start and ensure cleanup of sync mechanisms 16 //pm.fetcher.Start() 17 //defer pm.fetcher.Stop() 18 defer pm.downloader.Terminate() 19 20 // Wait for different events to fire synchronisation operations 21 //forceSync := time.Tick(forceSyncCycle) 22 for { 23 select { 24 case <-pm.newPeerCh: 25 /* // Make sure we have peers to select from, then sync 26 if pm.peers.Len() < minDesiredPeerCount { 27 break 28 } 29 go pm.synchronise(pm.peers.BestPeer()) 30 */ 31 /*case <-forceSync: 32 // Force a sync even if not enough peers are present 33 go pm.synchronise(pm.peers.BestPeer()) 34 */ 35 case <-pm.noMorePeers: 36 return 37 } 38 } 39 } 40 41 func (pm *ProtocolManager) needToSync(peerHead blockInfo) bool { 42 head := pm.blockchain.CurrentHeader() 43 currentTd := core.GetTd(pm.chainDb, head.Hash(), head.Number.Uint64()) 44 return currentTd != nil && peerHead.Td.Cmp(currentTd) > 0 45 } 46 47 // synchronise tries to sync up our local block chain with a remote peer. 48 func (pm *ProtocolManager) synchronise(peer *peer) { 49 // Short circuit if no peers are available 50 if peer == nil { 51 return 52 } 53 54 // Make sure the peer's TD is higher than our own. 55 if !pm.needToSync(peer.headBlockInfo()) { 56 return 57 } 58 59 ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) 60 defer cancel() 61 pm.blockchain.(*light.LightChain).SyncCht(ctx) 62 pm.downloader.Synchronise(peer.id, peer.Head(), peer.Td(), downloader.LightSync) 63 }