github.com/calmw/ethereum@v0.1.1/les/fetcher.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  	"math/big"
    21  	"math/rand"
    22  	"sync"
    23  	"time"
    24  
    25  	"github.com/calmw/ethereum/common"
    26  	"github.com/calmw/ethereum/consensus"
    27  	"github.com/calmw/ethereum/core"
    28  	"github.com/calmw/ethereum/core/rawdb"
    29  	"github.com/calmw/ethereum/core/types"
    30  	"github.com/calmw/ethereum/ethdb"
    31  	"github.com/calmw/ethereum/les/fetcher"
    32  	"github.com/calmw/ethereum/light"
    33  	"github.com/calmw/ethereum/log"
    34  	"github.com/calmw/ethereum/p2p/enode"
    35  )
    36  
    37  const (
    38  	blockDelayTimeout    = 10 * time.Second       // Timeout for retrieving the headers from the peer
    39  	gatherSlack          = 100 * time.Millisecond // Interval used to collate almost-expired requests
    40  	cachedAnnosThreshold = 64                     // The maximum queued announcements
    41  )
    42  
    43  // announce represents an new block announcement from the les server.
    44  type announce struct {
    45  	data   *announceData
    46  	trust  bool
    47  	peerid enode.ID
    48  }
    49  
    50  // request represents a record when the header request is sent.
    51  type request struct {
    52  	reqid  uint64
    53  	peerid enode.ID
    54  	sendAt time.Time
    55  	hash   common.Hash
    56  }
    57  
    58  // response represents a response packet from network as well as a channel
    59  // to return all un-requested data.
    60  type response struct {
    61  	reqid   uint64
    62  	headers []*types.Header
    63  	peerid  enode.ID
    64  	remain  chan []*types.Header
    65  }
    66  
    67  // fetcherPeer holds the fetcher-specific information for each active peer
    68  type fetcherPeer struct {
    69  	latest *announceData // The latest announcement sent from the peer
    70  
    71  	// These following two fields can track the latest announces
    72  	// from the peer with limited size for caching. We hold the
    73  	// assumption that all enqueued announces are td-monotonic.
    74  	announces map[common.Hash]*announce // Announcement map
    75  	fifo      []common.Hash             // FIFO announces list
    76  }
    77  
    78  // addAnno enqueues an new trusted announcement. If the queued announces overflow,
    79  // evict from the oldest.
    80  func (fp *fetcherPeer) addAnno(anno *announce) {
    81  	// Short circuit if the anno already exists. In normal case it should
    82  	// never happen since only monotonic anno is accepted. But the adversary
    83  	// may feed us fake announces with higher td but same hash. In this case,
    84  	// ignore the anno anyway.
    85  	hash := anno.data.Hash
    86  	if _, exist := fp.announces[hash]; exist {
    87  		return
    88  	}
    89  	fp.announces[hash] = anno
    90  	fp.fifo = append(fp.fifo, hash)
    91  
    92  	// Evict oldest if the announces are oversized.
    93  	if len(fp.fifo)-cachedAnnosThreshold > 0 {
    94  		for i := 0; i < len(fp.fifo)-cachedAnnosThreshold; i++ {
    95  			delete(fp.announces, fp.fifo[i])
    96  		}
    97  		copy(fp.fifo, fp.fifo[len(fp.fifo)-cachedAnnosThreshold:])
    98  		fp.fifo = fp.fifo[:cachedAnnosThreshold]
    99  	}
   100  }
   101  
   102  // forwardAnno removes all announces from the map with a number lower than
   103  // the provided threshold.
   104  func (fp *fetcherPeer) forwardAnno(td *big.Int) []*announce {
   105  	var (
   106  		cutset  int
   107  		evicted []*announce
   108  	)
   109  	for ; cutset < len(fp.fifo); cutset++ {
   110  		anno := fp.announces[fp.fifo[cutset]]
   111  		if anno == nil {
   112  			continue // In theory it should never ever happen
   113  		}
   114  		if anno.data.Td.Cmp(td) > 0 {
   115  			break
   116  		}
   117  		evicted = append(evicted, anno)
   118  		delete(fp.announces, anno.data.Hash)
   119  	}
   120  	if cutset > 0 {
   121  		copy(fp.fifo, fp.fifo[cutset:])
   122  		fp.fifo = fp.fifo[:len(fp.fifo)-cutset]
   123  	}
   124  	return evicted
   125  }
   126  
   127  // lightFetcher implements retrieval of newly announced headers. It reuses
   128  // the eth.BlockFetcher as the underlying fetcher but adding more additional
   129  // rules: e.g. evict "timeout" peers.
   130  type lightFetcher struct {
   131  	// Various handlers
   132  	ulc     *ulc
   133  	chaindb ethdb.Database
   134  	reqDist *requestDistributor
   135  	peerset *serverPeerSet        // The global peerset of light client which shared by all components
   136  	chain   *light.LightChain     // The local light chain which maintains the canonical header chain.
   137  	fetcher *fetcher.BlockFetcher // The underlying fetcher which takes care block header retrieval.
   138  
   139  	// Peerset maintained by fetcher
   140  	plock sync.RWMutex
   141  	peers map[enode.ID]*fetcherPeer
   142  
   143  	// Various channels
   144  	announceCh chan *announce
   145  	requestCh  chan *request
   146  	deliverCh  chan *response
   147  	syncDone   chan *types.Header
   148  
   149  	closeCh chan struct{}
   150  	wg      sync.WaitGroup
   151  
   152  	// Callback
   153  	synchronise func(peer *serverPeer)
   154  
   155  	// Test fields or hooks
   156  	newHeadHook func(*types.Header)
   157  }
   158  
   159  // newLightFetcher creates a light fetcher instance.
   160  func newLightFetcher(chain *light.LightChain, engine consensus.Engine, peers *serverPeerSet, ulc *ulc, chaindb ethdb.Database, reqDist *requestDistributor, syncFn func(p *serverPeer)) *lightFetcher {
   161  	// Construct the fetcher by offering all necessary APIs
   162  	validator := func(header *types.Header) error {
   163  		// Disable seal verification explicitly if we are running in ulc mode.
   164  		return engine.VerifyHeader(chain, header)
   165  	}
   166  	heighter := func() uint64 { return chain.CurrentHeader().Number.Uint64() }
   167  	dropper := func(id string) { peers.unregister(id) }
   168  	inserter := func(headers []*types.Header) (int, error) { return chain.InsertHeaderChain(headers) }
   169  	f := &lightFetcher{
   170  		ulc:         ulc,
   171  		peerset:     peers,
   172  		chaindb:     chaindb,
   173  		chain:       chain,
   174  		reqDist:     reqDist,
   175  		fetcher:     fetcher.NewBlockFetcher(true, chain.GetHeaderByHash, nil, validator, nil, heighter, inserter, nil, dropper),
   176  		peers:       make(map[enode.ID]*fetcherPeer),
   177  		synchronise: syncFn,
   178  		announceCh:  make(chan *announce),
   179  		requestCh:   make(chan *request),
   180  		deliverCh:   make(chan *response),
   181  		syncDone:    make(chan *types.Header),
   182  		closeCh:     make(chan struct{}),
   183  	}
   184  	peers.subscribe(f)
   185  	return f
   186  }
   187  
   188  func (f *lightFetcher) start() {
   189  	f.wg.Add(1)
   190  	f.fetcher.Start()
   191  	go f.mainloop()
   192  }
   193  
   194  func (f *lightFetcher) stop() {
   195  	close(f.closeCh)
   196  	f.fetcher.Stop()
   197  	f.wg.Wait()
   198  }
   199  
   200  // registerPeer adds an new peer to the fetcher's peer set
   201  func (f *lightFetcher) registerPeer(p *serverPeer) {
   202  	f.plock.Lock()
   203  	defer f.plock.Unlock()
   204  
   205  	f.peers[p.ID()] = &fetcherPeer{announces: make(map[common.Hash]*announce)}
   206  }
   207  
   208  // unregisterPeer removes the specified peer from the fetcher's peer set
   209  func (f *lightFetcher) unregisterPeer(p *serverPeer) {
   210  	f.plock.Lock()
   211  	defer f.plock.Unlock()
   212  
   213  	delete(f.peers, p.ID())
   214  }
   215  
   216  // peer returns the peer from the fetcher peerset.
   217  func (f *lightFetcher) peer(id enode.ID) *fetcherPeer {
   218  	f.plock.RLock()
   219  	defer f.plock.RUnlock()
   220  
   221  	return f.peers[id]
   222  }
   223  
   224  // forEachPeer iterates the fetcher peerset, abort the iteration if the
   225  // callback returns false.
   226  func (f *lightFetcher) forEachPeer(check func(id enode.ID, p *fetcherPeer) bool) {
   227  	f.plock.RLock()
   228  	defer f.plock.RUnlock()
   229  
   230  	for id, peer := range f.peers {
   231  		if !check(id, peer) {
   232  			return
   233  		}
   234  	}
   235  }
   236  
   237  // mainloop is the main event loop of the light fetcher, which is responsible for
   238  //
   239  //   - announcement maintenance(ulc)
   240  //
   241  //     If we are running in ultra light client mode, then all announcements from
   242  //     the trusted servers are maintained. If the same announcements from trusted
   243  //     servers reach the threshold, then the relevant header is requested for retrieval.
   244  //
   245  //   - block header retrieval
   246  //     Whenever we receive announce with higher td compared with local chain, the
   247  //     request will be made for header retrieval.
   248  //
   249  //   - re-sync trigger
   250  //     If the local chain lags too much, then the fetcher will enter "synchronise"
   251  //     mode to retrieve missing headers in batch.
   252  func (f *lightFetcher) mainloop() {
   253  	defer f.wg.Done()
   254  
   255  	var (
   256  		syncInterval = uint64(1) // Interval used to trigger a light resync.
   257  		syncing      bool        // Indicator whether the client is syncing
   258  
   259  		ulc          = f.ulc != nil
   260  		headCh       = make(chan core.ChainHeadEvent, 100)
   261  		fetching     = make(map[uint64]*request)
   262  		requestTimer = time.NewTimer(0)
   263  
   264  		// Local status
   265  		localHead = f.chain.CurrentHeader()
   266  		localTd   = f.chain.GetTd(localHead.Hash(), localHead.Number.Uint64())
   267  	)
   268  	defer requestTimer.Stop()
   269  	sub := f.chain.SubscribeChainHeadEvent(headCh)
   270  	defer sub.Unsubscribe()
   271  
   272  	// reset updates the local status with given header.
   273  	reset := func(header *types.Header) {
   274  		localHead = header
   275  		localTd = f.chain.GetTd(header.Hash(), header.Number.Uint64())
   276  	}
   277  	// trustedHeader returns an indicator whether the header is regarded as
   278  	// trusted. If we are running in the ulc mode, only when we receive enough
   279  	// same announcement from trusted server, the header will be trusted.
   280  	trustedHeader := func(hash common.Hash, number uint64) (bool, []enode.ID) {
   281  		var (
   282  			agreed  []enode.ID
   283  			trusted bool
   284  		)
   285  		f.forEachPeer(func(id enode.ID, p *fetcherPeer) bool {
   286  			if anno := p.announces[hash]; anno != nil && anno.trust && anno.data.Number == number {
   287  				agreed = append(agreed, id)
   288  				if 100*len(agreed)/len(f.ulc.keys) >= f.ulc.fraction {
   289  					trusted = true
   290  					return false // abort iteration
   291  				}
   292  			}
   293  			return true
   294  		})
   295  		return trusted, agreed
   296  	}
   297  	for {
   298  		select {
   299  		case anno := <-f.announceCh:
   300  			peerid, data := anno.peerid, anno.data
   301  			log.Debug("Received new announce", "peer", peerid, "number", data.Number, "hash", data.Hash, "reorg", data.ReorgDepth)
   302  
   303  			peer := f.peer(peerid)
   304  			if peer == nil {
   305  				log.Debug("Receive announce from unknown peer", "peer", peerid)
   306  				continue
   307  			}
   308  			// Announced tds should be strictly monotonic, drop the peer if
   309  			// the announce is out-of-order.
   310  			if peer.latest != nil && data.Td.Cmp(peer.latest.Td) <= 0 {
   311  				f.peerset.unregister(peerid.String())
   312  				log.Debug("Non-monotonic td", "peer", peerid, "current", data.Td, "previous", peer.latest.Td)
   313  				continue
   314  			}
   315  			peer.latest = data
   316  
   317  			// Filter out any stale announce, the local chain is ahead of announce
   318  			if localTd != nil && data.Td.Cmp(localTd) <= 0 {
   319  				continue
   320  			}
   321  			peer.addAnno(anno)
   322  
   323  			// If we are not syncing, try to trigger a single retrieval or re-sync
   324  			if !ulc && !syncing {
   325  				// Two scenarios lead to re-sync:
   326  				// - reorg happens
   327  				// - local chain lags
   328  				// We can't retrieve the parent of the announce by single retrieval
   329  				// in both cases, so resync is necessary.
   330  				if data.Number > localHead.Number.Uint64()+syncInterval || data.ReorgDepth > 0 {
   331  					syncing = true
   332  					go f.startSync(peerid)
   333  					log.Debug("Trigger light sync", "peer", peerid, "local", localHead.Number, "localhash", localHead.Hash(), "remote", data.Number, "remotehash", data.Hash)
   334  					continue
   335  				}
   336  				f.fetcher.Notify(peerid.String(), data.Hash, data.Number, time.Now(), f.requestHeaderByHash(peerid), nil)
   337  				log.Debug("Trigger header retrieval", "peer", peerid, "number", data.Number, "hash", data.Hash)
   338  			}
   339  			// Keep collecting announces from trusted server even we are syncing.
   340  			if ulc && anno.trust {
   341  				// Notify underlying fetcher to retrieve header or trigger a resync if
   342  				// we have receive enough announcements from trusted server.
   343  				trusted, agreed := trustedHeader(data.Hash, data.Number)
   344  				if trusted && !syncing {
   345  					if data.Number > localHead.Number.Uint64()+syncInterval || data.ReorgDepth > 0 {
   346  						syncing = true
   347  						go f.startSync(peerid)
   348  						log.Debug("Trigger trusted light sync", "local", localHead.Number, "localhash", localHead.Hash(), "remote", data.Number, "remotehash", data.Hash)
   349  						continue
   350  					}
   351  					p := agreed[rand.Intn(len(agreed))]
   352  					f.fetcher.Notify(p.String(), data.Hash, data.Number, time.Now(), f.requestHeaderByHash(p), nil)
   353  					log.Debug("Trigger trusted header retrieval", "number", data.Number, "hash", data.Hash)
   354  				}
   355  			}
   356  
   357  		case req := <-f.requestCh:
   358  			fetching[req.reqid] = req // Tracking all in-flight requests for response latency statistic.
   359  			if len(fetching) == 1 {
   360  				f.rescheduleTimer(fetching, requestTimer)
   361  			}
   362  
   363  		case <-requestTimer.C:
   364  			for reqid, request := range fetching {
   365  				if time.Since(request.sendAt) > blockDelayTimeout-gatherSlack {
   366  					delete(fetching, reqid)
   367  					f.peerset.unregister(request.peerid.String())
   368  					log.Debug("Request timeout", "peer", request.peerid, "reqid", reqid)
   369  				}
   370  			}
   371  			f.rescheduleTimer(fetching, requestTimer)
   372  
   373  		case resp := <-f.deliverCh:
   374  			if req := fetching[resp.reqid]; req != nil {
   375  				delete(fetching, resp.reqid)
   376  				f.rescheduleTimer(fetching, requestTimer)
   377  
   378  				// The underlying fetcher does not check the consistency of request and response.
   379  				// The adversary can send the fake announces with invalid hash and number but always
   380  				// delivery some mismatched header. So it can't be punished by the underlying fetcher.
   381  				// We have to add two more rules here to detect.
   382  				if len(resp.headers) != 1 {
   383  					f.peerset.unregister(req.peerid.String())
   384  					log.Debug("Deliver more than requested", "peer", req.peerid, "reqid", req.reqid)
   385  					continue
   386  				}
   387  				if resp.headers[0].Hash() != req.hash {
   388  					f.peerset.unregister(req.peerid.String())
   389  					log.Debug("Deliver invalid header", "peer", req.peerid, "reqid", req.reqid)
   390  					continue
   391  				}
   392  				resp.remain <- f.fetcher.FilterHeaders(resp.peerid.String(), resp.headers, time.Now())
   393  			} else {
   394  				// Discard the entire packet no matter it's a timeout response or unexpected one.
   395  				resp.remain <- resp.headers
   396  			}
   397  
   398  		case ev := <-headCh:
   399  			// Short circuit if we are still syncing.
   400  			if syncing {
   401  				continue
   402  			}
   403  			reset(ev.Block.Header())
   404  
   405  			// Clean stale announcements from les-servers.
   406  			var droplist []enode.ID
   407  			f.forEachPeer(func(id enode.ID, p *fetcherPeer) bool {
   408  				removed := p.forwardAnno(localTd)
   409  				for _, anno := range removed {
   410  					if header := f.chain.GetHeaderByHash(anno.data.Hash); header != nil {
   411  						if header.Number.Uint64() != anno.data.Number {
   412  							droplist = append(droplist, id)
   413  							break
   414  						}
   415  						// In theory td should exists.
   416  						td := f.chain.GetTd(anno.data.Hash, anno.data.Number)
   417  						if td != nil && td.Cmp(anno.data.Td) != 0 {
   418  							droplist = append(droplist, id)
   419  							break
   420  						}
   421  					}
   422  				}
   423  				return true
   424  			})
   425  			for _, id := range droplist {
   426  				f.peerset.unregister(id.String())
   427  				log.Debug("Kicked out peer for invalid announcement")
   428  			}
   429  			if f.newHeadHook != nil {
   430  				f.newHeadHook(localHead)
   431  			}
   432  
   433  		case origin := <-f.syncDone:
   434  			syncing = false // Reset the status
   435  
   436  			// Rewind all untrusted headers for ulc mode.
   437  			if ulc {
   438  				head := f.chain.CurrentHeader()
   439  				ancestor := rawdb.FindCommonAncestor(f.chaindb, origin, head)
   440  
   441  				// Recap the ancestor with genesis header in case the ancestor
   442  				// is not found. It can happen the original head is before the
   443  				// checkpoint while the synced headers are after it. In this
   444  				// case there is no ancestor between them.
   445  				if ancestor == nil {
   446  					ancestor = f.chain.Genesis().Header()
   447  				}
   448  				var untrusted []common.Hash
   449  				for head.Number.Cmp(ancestor.Number) > 0 {
   450  					hash, number := head.Hash(), head.Number.Uint64()
   451  					if trusted, _ := trustedHeader(hash, number); trusted {
   452  						break
   453  					}
   454  					untrusted = append(untrusted, hash)
   455  					head = f.chain.GetHeader(head.ParentHash, number-1)
   456  					if head == nil {
   457  						break // all the synced headers will be dropped
   458  					}
   459  				}
   460  				if len(untrusted) > 0 {
   461  					for i, j := 0, len(untrusted)-1; i < j; i, j = i+1, j-1 {
   462  						untrusted[i], untrusted[j] = untrusted[j], untrusted[i]
   463  					}
   464  					f.chain.Rollback(untrusted)
   465  				}
   466  			}
   467  			// Reset local status.
   468  			reset(f.chain.CurrentHeader())
   469  			if f.newHeadHook != nil {
   470  				f.newHeadHook(localHead)
   471  			}
   472  			log.Debug("light sync finished", "number", localHead.Number, "hash", localHead.Hash())
   473  
   474  		case <-f.closeCh:
   475  			return
   476  		}
   477  	}
   478  }
   479  
   480  // announce processes a new announcement message received from a peer.
   481  func (f *lightFetcher) announce(p *serverPeer, head *announceData) {
   482  	select {
   483  	case f.announceCh <- &announce{peerid: p.ID(), trust: p.trusted, data: head}:
   484  	case <-f.closeCh:
   485  		return
   486  	}
   487  }
   488  
   489  // trackRequest sends a reqID to main loop for in-flight request tracking.
   490  func (f *lightFetcher) trackRequest(peerid enode.ID, reqid uint64, hash common.Hash) {
   491  	select {
   492  	case f.requestCh <- &request{reqid: reqid, peerid: peerid, sendAt: time.Now(), hash: hash}:
   493  	case <-f.closeCh:
   494  	}
   495  }
   496  
   497  // requestHeaderByHash constructs a header retrieval request and sends it to
   498  // local request distributor.
   499  //
   500  // Note, we rely on the underlying eth/fetcher to retrieve and validate the
   501  // response, so that we have to obey the rule of eth/fetcher which only accepts
   502  // the response from given peer.
   503  func (f *lightFetcher) requestHeaderByHash(peerid enode.ID) func(common.Hash) error {
   504  	return func(hash common.Hash) error {
   505  		req := &distReq{
   506  			getCost: func(dp distPeer) uint64 { return dp.(*serverPeer).getRequestCost(GetBlockHeadersMsg, 1) },
   507  			canSend: func(dp distPeer) bool { return dp.(*serverPeer).ID() == peerid },
   508  			request: func(dp distPeer) func() {
   509  				peer, id := dp.(*serverPeer), rand.Uint64()
   510  				cost := peer.getRequestCost(GetBlockHeadersMsg, 1)
   511  				peer.fcServer.QueuedRequest(id, cost)
   512  
   513  				return func() {
   514  					f.trackRequest(peer.ID(), id, hash)
   515  					peer.requestHeadersByHash(id, hash, 1, 0, false)
   516  				}
   517  			},
   518  		}
   519  		f.reqDist.queue(req)
   520  		return nil
   521  	}
   522  }
   523  
   524  // startSync invokes synchronisation callback to start syncing.
   525  func (f *lightFetcher) startSync(id enode.ID) {
   526  	defer func(header *types.Header) {
   527  		f.syncDone <- header
   528  	}(f.chain.CurrentHeader())
   529  
   530  	peer := f.peerset.peer(id.String())
   531  	if peer == nil || peer.onlyAnnounce {
   532  		return
   533  	}
   534  	f.synchronise(peer)
   535  }
   536  
   537  // deliverHeaders delivers header download request responses for processing
   538  func (f *lightFetcher) deliverHeaders(peer *serverPeer, reqid uint64, headers []*types.Header) []*types.Header {
   539  	remain := make(chan []*types.Header, 1)
   540  	select {
   541  	case f.deliverCh <- &response{reqid: reqid, headers: headers, peerid: peer.ID(), remain: remain}:
   542  	case <-f.closeCh:
   543  		return nil
   544  	}
   545  	return <-remain
   546  }
   547  
   548  // rescheduleTimer resets the specified timeout timer to the next request timeout.
   549  func (f *lightFetcher) rescheduleTimer(requests map[uint64]*request, timer *time.Timer) {
   550  	// Short circuit if no inflight requests
   551  	if len(requests) == 0 {
   552  		timer.Stop()
   553  		return
   554  	}
   555  	// Otherwise find the earliest expiring request
   556  	earliest := time.Now()
   557  	for _, req := range requests {
   558  		if earliest.After(req.sendAt) {
   559  			earliest = req.sendAt
   560  		}
   561  	}
   562  	timer.Reset(blockDelayTimeout - time.Since(earliest))
   563  }