github.com/calmw/ethereum@v0.1.1/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  	"time"
    21  
    22  	"github.com/calmw/ethereum/common"
    23  	"github.com/calmw/ethereum/core/rawdb"
    24  	"github.com/calmw/ethereum/les/downloader"
    25  	"github.com/calmw/ethereum/log"
    26  )
    27  
    28  // synchronise tries to sync up our local chain with a remote peer.
    29  func (h *clientHandler) synchronise(peer *serverPeer) {
    30  	// Short circuit if the peer is nil.
    31  	if peer == nil {
    32  		return
    33  	}
    34  	// Make sure the peer's TD is higher than our own.
    35  	latest := h.backend.blockchain.CurrentHeader()
    36  	currentTd := rawdb.ReadTd(h.backend.chainDb, latest.Hash(), latest.Number.Uint64())
    37  	if currentTd != nil && peer.Td().Cmp(currentTd) < 0 {
    38  		return
    39  	}
    40  	// Notify testing framework if syncing has completed (for testing purpose).
    41  	defer func() {
    42  		if h.syncEnd != nil {
    43  			h.syncEnd(h.backend.blockchain.CurrentHeader())
    44  		}
    45  	}()
    46  	start := time.Now()
    47  	if h.syncStart != nil {
    48  		h.syncStart(h.backend.blockchain.CurrentHeader())
    49  	}
    50  	// Fetch the remaining block headers based on the current chain header.
    51  	if err := h.downloader.Synchronise(peer.id, peer.Head(), peer.Td(), downloader.LightSync); err != nil {
    52  		log.Debug("Synchronise failed", "reason", err)
    53  		return
    54  	}
    55  	log.Debug("Synchronise finished", "elapsed", common.PrettyDuration(time.Since(start)))
    56  }