github.com/tacshi/go-ethereum@v0.0.0-20230616113857-84a434e20921/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/tacshi/go-ethereum/common" 26 "github.com/tacshi/go-ethereum/consensus" 27 "github.com/tacshi/go-ethereum/core" 28 "github.com/tacshi/go-ethereum/core/rawdb" 29 "github.com/tacshi/go-ethereum/core/types" 30 "github.com/tacshi/go-ethereum/ethdb" 31 "github.com/tacshi/go-ethereum/les/fetcher" 32 "github.com/tacshi/go-ethereum/light" 33 "github.com/tacshi/go-ethereum/log" 34 "github.com/tacshi/go-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, ulc == nil) 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) { 169 // Disable PoW checking explicitly if we are running in ulc mode. 170 checkFreq := 1 171 if ulc != nil { 172 checkFreq = 0 173 } 174 return chain.InsertHeaderChain(headers, checkFreq) 175 } 176 f := &lightFetcher{ 177 ulc: ulc, 178 peerset: peers, 179 chaindb: chaindb, 180 chain: chain, 181 reqDist: reqDist, 182 fetcher: fetcher.NewBlockFetcher(true, chain.GetHeaderByHash, nil, validator, nil, heighter, inserter, nil, dropper), 183 peers: make(map[enode.ID]*fetcherPeer), 184 synchronise: syncFn, 185 announceCh: make(chan *announce), 186 requestCh: make(chan *request), 187 deliverCh: make(chan *response), 188 syncDone: make(chan *types.Header), 189 closeCh: make(chan struct{}), 190 } 191 peers.subscribe(f) 192 return f 193 } 194 195 func (f *lightFetcher) start() { 196 f.wg.Add(1) 197 f.fetcher.Start() 198 go f.mainloop() 199 } 200 201 func (f *lightFetcher) stop() { 202 close(f.closeCh) 203 f.fetcher.Stop() 204 f.wg.Wait() 205 } 206 207 // registerPeer adds an new peer to the fetcher's peer set 208 func (f *lightFetcher) registerPeer(p *serverPeer) { 209 f.plock.Lock() 210 defer f.plock.Unlock() 211 212 f.peers[p.ID()] = &fetcherPeer{announces: make(map[common.Hash]*announce)} 213 } 214 215 // unregisterPeer removes the specified peer from the fetcher's peer set 216 func (f *lightFetcher) unregisterPeer(p *serverPeer) { 217 f.plock.Lock() 218 defer f.plock.Unlock() 219 220 delete(f.peers, p.ID()) 221 } 222 223 // peer returns the peer from the fetcher peerset. 224 func (f *lightFetcher) peer(id enode.ID) *fetcherPeer { 225 f.plock.RLock() 226 defer f.plock.RUnlock() 227 228 return f.peers[id] 229 } 230 231 // forEachPeer iterates the fetcher peerset, abort the iteration if the 232 // callback returns false. 233 func (f *lightFetcher) forEachPeer(check func(id enode.ID, p *fetcherPeer) bool) { 234 f.plock.RLock() 235 defer f.plock.RUnlock() 236 237 for id, peer := range f.peers { 238 if !check(id, peer) { 239 return 240 } 241 } 242 } 243 244 // mainloop is the main event loop of the light fetcher, which is responsible for 245 // 246 // - announcement maintenance(ulc) 247 // 248 // If we are running in ultra light client mode, then all announcements from 249 // the trusted servers are maintained. If the same announcements from trusted 250 // servers reach the threshold, then the relevant header is requested for retrieval. 251 // 252 // - block header retrieval 253 // Whenever we receive announce with higher td compared with local chain, the 254 // request will be made for header retrieval. 255 // 256 // - re-sync trigger 257 // If the local chain lags too much, then the fetcher will enter "synchronise" 258 // mode to retrieve missing headers in batch. 259 func (f *lightFetcher) mainloop() { 260 defer f.wg.Done() 261 262 var ( 263 syncInterval = uint64(1) // Interval used to trigger a light resync. 264 syncing bool // Indicator whether the client is syncing 265 266 ulc = f.ulc != nil 267 headCh = make(chan core.ChainHeadEvent, 100) 268 fetching = make(map[uint64]*request) 269 requestTimer = time.NewTimer(0) 270 271 // Local status 272 localHead = f.chain.CurrentHeader() 273 localTd = f.chain.GetTd(localHead.Hash(), localHead.Number.Uint64()) 274 ) 275 defer requestTimer.Stop() 276 sub := f.chain.SubscribeChainHeadEvent(headCh) 277 defer sub.Unsubscribe() 278 279 // reset updates the local status with given header. 280 reset := func(header *types.Header) { 281 localHead = header 282 localTd = f.chain.GetTd(header.Hash(), header.Number.Uint64()) 283 } 284 // trustedHeader returns an indicator whether the header is regarded as 285 // trusted. If we are running in the ulc mode, only when we receive enough 286 // same announcement from trusted server, the header will be trusted. 287 trustedHeader := func(hash common.Hash, number uint64) (bool, []enode.ID) { 288 var ( 289 agreed []enode.ID 290 trusted bool 291 ) 292 f.forEachPeer(func(id enode.ID, p *fetcherPeer) bool { 293 if anno := p.announces[hash]; anno != nil && anno.trust && anno.data.Number == number { 294 agreed = append(agreed, id) 295 if 100*len(agreed)/len(f.ulc.keys) >= f.ulc.fraction { 296 trusted = true 297 return false // abort iteration 298 } 299 } 300 return true 301 }) 302 return trusted, agreed 303 } 304 for { 305 select { 306 case anno := <-f.announceCh: 307 peerid, data := anno.peerid, anno.data 308 log.Debug("Received new announce", "peer", peerid, "number", data.Number, "hash", data.Hash, "reorg", data.ReorgDepth) 309 310 peer := f.peer(peerid) 311 if peer == nil { 312 log.Debug("Receive announce from unknown peer", "peer", peerid) 313 continue 314 } 315 // Announced tds should be strictly monotonic, drop the peer if 316 // the announce is out-of-order. 317 if peer.latest != nil && data.Td.Cmp(peer.latest.Td) <= 0 { 318 f.peerset.unregister(peerid.String()) 319 log.Debug("Non-monotonic td", "peer", peerid, "current", data.Td, "previous", peer.latest.Td) 320 continue 321 } 322 peer.latest = data 323 324 // Filter out any stale announce, the local chain is ahead of announce 325 if localTd != nil && data.Td.Cmp(localTd) <= 0 { 326 continue 327 } 328 peer.addAnno(anno) 329 330 // If we are not syncing, try to trigger a single retrieval or re-sync 331 if !ulc && !syncing { 332 // Two scenarios lead to re-sync: 333 // - reorg happens 334 // - local chain lags 335 // We can't retrieve the parent of the announce by single retrieval 336 // in both cases, so resync is necessary. 337 if data.Number > localHead.Number.Uint64()+syncInterval || data.ReorgDepth > 0 { 338 syncing = true 339 go f.startSync(peerid) 340 log.Debug("Trigger light sync", "peer", peerid, "local", localHead.Number, "localhash", localHead.Hash(), "remote", data.Number, "remotehash", data.Hash) 341 continue 342 } 343 f.fetcher.Notify(peerid.String(), data.Hash, data.Number, time.Now(), f.requestHeaderByHash(peerid), nil) 344 log.Debug("Trigger header retrieval", "peer", peerid, "number", data.Number, "hash", data.Hash) 345 } 346 // Keep collecting announces from trusted server even we are syncing. 347 if ulc && anno.trust { 348 // Notify underlying fetcher to retrieve header or trigger a resync if 349 // we have receive enough announcements from trusted server. 350 trusted, agreed := trustedHeader(data.Hash, data.Number) 351 if trusted && !syncing { 352 if data.Number > localHead.Number.Uint64()+syncInterval || data.ReorgDepth > 0 { 353 syncing = true 354 go f.startSync(peerid) 355 log.Debug("Trigger trusted light sync", "local", localHead.Number, "localhash", localHead.Hash(), "remote", data.Number, "remotehash", data.Hash) 356 continue 357 } 358 p := agreed[rand.Intn(len(agreed))] 359 f.fetcher.Notify(p.String(), data.Hash, data.Number, time.Now(), f.requestHeaderByHash(p), nil) 360 log.Debug("Trigger trusted header retrieval", "number", data.Number, "hash", data.Hash) 361 } 362 } 363 364 case req := <-f.requestCh: 365 fetching[req.reqid] = req // Tracking all in-flight requests for response latency statistic. 366 if len(fetching) == 1 { 367 f.rescheduleTimer(fetching, requestTimer) 368 } 369 370 case <-requestTimer.C: 371 for reqid, request := range fetching { 372 if time.Since(request.sendAt) > blockDelayTimeout-gatherSlack { 373 delete(fetching, reqid) 374 f.peerset.unregister(request.peerid.String()) 375 log.Debug("Request timeout", "peer", request.peerid, "reqid", reqid) 376 } 377 } 378 f.rescheduleTimer(fetching, requestTimer) 379 380 case resp := <-f.deliverCh: 381 if req := fetching[resp.reqid]; req != nil { 382 delete(fetching, resp.reqid) 383 f.rescheduleTimer(fetching, requestTimer) 384 385 // The underlying fetcher does not check the consistency of request and response. 386 // The adversary can send the fake announces with invalid hash and number but always 387 // delivery some mismatched header. So it can't be punished by the underlying fetcher. 388 // We have to add two more rules here to detect. 389 if len(resp.headers) != 1 { 390 f.peerset.unregister(req.peerid.String()) 391 log.Debug("Deliver more than requested", "peer", req.peerid, "reqid", req.reqid) 392 continue 393 } 394 if resp.headers[0].Hash() != req.hash { 395 f.peerset.unregister(req.peerid.String()) 396 log.Debug("Deliver invalid header", "peer", req.peerid, "reqid", req.reqid) 397 continue 398 } 399 resp.remain <- f.fetcher.FilterHeaders(resp.peerid.String(), resp.headers, time.Now()) 400 } else { 401 // Discard the entire packet no matter it's a timeout response or unexpected one. 402 resp.remain <- resp.headers 403 } 404 405 case ev := <-headCh: 406 // Short circuit if we are still syncing. 407 if syncing { 408 continue 409 } 410 reset(ev.Block.Header()) 411 412 // Clean stale announcements from les-servers. 413 var droplist []enode.ID 414 f.forEachPeer(func(id enode.ID, p *fetcherPeer) bool { 415 removed := p.forwardAnno(localTd) 416 for _, anno := range removed { 417 if header := f.chain.GetHeaderByHash(anno.data.Hash); header != nil { 418 if header.Number.Uint64() != anno.data.Number { 419 droplist = append(droplist, id) 420 break 421 } 422 // In theory td should exists. 423 td := f.chain.GetTd(anno.data.Hash, anno.data.Number) 424 if td != nil && td.Cmp(anno.data.Td) != 0 { 425 droplist = append(droplist, id) 426 break 427 } 428 } 429 } 430 return true 431 }) 432 for _, id := range droplist { 433 f.peerset.unregister(id.String()) 434 log.Debug("Kicked out peer for invalid announcement") 435 } 436 if f.newHeadHook != nil { 437 f.newHeadHook(localHead) 438 } 439 440 case origin := <-f.syncDone: 441 syncing = false // Reset the status 442 443 // Rewind all untrusted headers for ulc mode. 444 if ulc { 445 head := f.chain.CurrentHeader() 446 ancestor := rawdb.FindCommonAncestor(f.chaindb, origin, head) 447 448 // Recap the ancestor with genesis header in case the ancestor 449 // is not found. It can happen the original head is before the 450 // checkpoint while the synced headers are after it. In this 451 // case there is no ancestor between them. 452 if ancestor == nil { 453 ancestor = f.chain.Genesis().Header() 454 } 455 var untrusted []common.Hash 456 for head.Number.Cmp(ancestor.Number) > 0 { 457 hash, number := head.Hash(), head.Number.Uint64() 458 if trusted, _ := trustedHeader(hash, number); trusted { 459 break 460 } 461 untrusted = append(untrusted, hash) 462 head = f.chain.GetHeader(head.ParentHash, number-1) 463 if head == nil { 464 break // all the synced headers will be dropped 465 } 466 } 467 if len(untrusted) > 0 { 468 for i, j := 0, len(untrusted)-1; i < j; i, j = i+1, j-1 { 469 untrusted[i], untrusted[j] = untrusted[j], untrusted[i] 470 } 471 f.chain.Rollback(untrusted) 472 } 473 } 474 // Reset local status. 475 reset(f.chain.CurrentHeader()) 476 if f.newHeadHook != nil { 477 f.newHeadHook(localHead) 478 } 479 log.Debug("light sync finished", "number", localHead.Number, "hash", localHead.Hash()) 480 481 case <-f.closeCh: 482 return 483 } 484 } 485 } 486 487 // announce processes a new announcement message received from a peer. 488 func (f *lightFetcher) announce(p *serverPeer, head *announceData) { 489 select { 490 case f.announceCh <- &announce{peerid: p.ID(), trust: p.trusted, data: head}: 491 case <-f.closeCh: 492 return 493 } 494 } 495 496 // trackRequest sends a reqID to main loop for in-flight request tracking. 497 func (f *lightFetcher) trackRequest(peerid enode.ID, reqid uint64, hash common.Hash) { 498 select { 499 case f.requestCh <- &request{reqid: reqid, peerid: peerid, sendAt: time.Now(), hash: hash}: 500 case <-f.closeCh: 501 } 502 } 503 504 // requestHeaderByHash constructs a header retrieval request and sends it to 505 // local request distributor. 506 // 507 // Note, we rely on the underlying eth/fetcher to retrieve and validate the 508 // response, so that we have to obey the rule of eth/fetcher which only accepts 509 // the response from given peer. 510 func (f *lightFetcher) requestHeaderByHash(peerid enode.ID) func(common.Hash) error { 511 return func(hash common.Hash) error { 512 req := &distReq{ 513 getCost: func(dp distPeer) uint64 { return dp.(*serverPeer).getRequestCost(GetBlockHeadersMsg, 1) }, 514 canSend: func(dp distPeer) bool { return dp.(*serverPeer).ID() == peerid }, 515 request: func(dp distPeer) func() { 516 peer, id := dp.(*serverPeer), rand.Uint64() 517 cost := peer.getRequestCost(GetBlockHeadersMsg, 1) 518 peer.fcServer.QueuedRequest(id, cost) 519 520 return func() { 521 f.trackRequest(peer.ID(), id, hash) 522 peer.requestHeadersByHash(id, hash, 1, 0, false) 523 } 524 }, 525 } 526 f.reqDist.queue(req) 527 return nil 528 } 529 } 530 531 // startSync invokes synchronisation callback to start syncing. 532 func (f *lightFetcher) startSync(id enode.ID) { 533 defer func(header *types.Header) { 534 f.syncDone <- header 535 }(f.chain.CurrentHeader()) 536 537 peer := f.peerset.peer(id.String()) 538 if peer == nil || peer.onlyAnnounce { 539 return 540 } 541 f.synchronise(peer) 542 } 543 544 // deliverHeaders delivers header download request responses for processing 545 func (f *lightFetcher) deliverHeaders(peer *serverPeer, reqid uint64, headers []*types.Header) []*types.Header { 546 remain := make(chan []*types.Header, 1) 547 select { 548 case f.deliverCh <- &response{reqid: reqid, headers: headers, peerid: peer.ID(), remain: remain}: 549 case <-f.closeCh: 550 return nil 551 } 552 return <-remain 553 } 554 555 // rescheduleTimer resets the specified timeout timer to the next request timeout. 556 func (f *lightFetcher) rescheduleTimer(requests map[uint64]*request, timer *time.Timer) { 557 // Short circuit if no inflight requests 558 if len(requests) == 0 { 559 timer.Stop() 560 return 561 } 562 // Otherwise find the earliest expiring request 563 earliest := time.Now() 564 for _, req := range requests { 565 if earliest.After(req.sendAt) { 566 earliest = req.sendAt 567 } 568 } 569 timer.Reset(blockDelayTimeout - time.Since(earliest)) 570 }