github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/eth/downloader/peer.go (about) 1 // Copyright 2015 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 // Contains the active peer-set of the downloader, maintaining both failures 18 // as well as reputation metrics to prioritize the block retrievals. 19 20 package downloader 21 22 import ( 23 "errors" 24 "math" 25 "math/big" 26 "sort" 27 "sync" 28 "sync/atomic" 29 "time" 30 31 "github.com/kisexp/xdchain/common" 32 "github.com/kisexp/xdchain/consensus" 33 "github.com/kisexp/xdchain/event" 34 "github.com/kisexp/xdchain/log" 35 ) 36 37 const ( 38 maxLackingHashes = 4096 // Maximum number of entries allowed on the list or lacking items 39 measurementImpact = 0.1 // The impact a single measurement has on a peer's final throughput value. 40 ) 41 42 var ( 43 errAlreadyFetching = errors.New("already fetching blocks from peer") 44 errAlreadyRegistered = errors.New("peer is already registered") 45 errNotRegistered = errors.New("peer is not registered") 46 ) 47 48 // peerConnection represents an active peer from which hashes and blocks are retrieved. 49 type peerConnection struct { 50 id string // Unique identifier of the peer 51 52 headerIdle int32 // Current header activity state of the peer (idle = 0, active = 1) 53 blockIdle int32 // Current block activity state of the peer (idle = 0, active = 1) 54 receiptIdle int32 // Current receipt activity state of the peer (idle = 0, active = 1) 55 stateIdle int32 // Current node data activity state of the peer (idle = 0, active = 1) 56 57 headerThroughput float64 // Number of headers measured to be retrievable per second 58 blockThroughput float64 // Number of blocks (bodies) measured to be retrievable per second 59 receiptThroughput float64 // Number of receipts measured to be retrievable per second 60 stateThroughput float64 // Number of node data pieces measured to be retrievable per second 61 62 rtt time.Duration // Request round trip time to track responsiveness (QoS) 63 64 headerStarted time.Time // Time instance when the last header fetch was started 65 blockStarted time.Time // Time instance when the last block (body) fetch was started 66 receiptStarted time.Time // Time instance when the last receipt fetch was started 67 stateStarted time.Time // Time instance when the last node data fetch was started 68 69 lacking map[common.Hash]struct{} // Set of hashes not to request (didn't have previously) 70 71 peer Peer 72 73 version int // Eth protocol version number to switch strategies 74 log log.Logger // Contextual logger to add extra infos to peer logs 75 lock sync.RWMutex 76 } 77 78 // LightPeer encapsulates the methods required to synchronise with a remote light peer. 79 type LightPeer interface { 80 Head() (common.Hash, *big.Int) 81 RequestHeadersByHash(common.Hash, int, int, bool) error 82 RequestHeadersByNumber(uint64, int, int, bool) error 83 } 84 85 // Peer encapsulates the methods required to synchronise with a remote full peer. 86 type Peer interface { 87 LightPeer 88 RequestBodies([]common.Hash) error 89 RequestReceipts([]common.Hash) error 90 RequestNodeData([]common.Hash) error 91 } 92 93 // lightPeerWrapper wraps a LightPeer struct, stubbing out the Peer-only methods. 94 type lightPeerWrapper struct { 95 peer LightPeer 96 } 97 98 func (w *lightPeerWrapper) Head() (common.Hash, *big.Int) { return w.peer.Head() } 99 func (w *lightPeerWrapper) RequestHeadersByHash(h common.Hash, amount int, skip int, reverse bool) error { 100 return w.peer.RequestHeadersByHash(h, amount, skip, reverse) 101 } 102 func (w *lightPeerWrapper) RequestHeadersByNumber(i uint64, amount int, skip int, reverse bool) error { 103 return w.peer.RequestHeadersByNumber(i, amount, skip, reverse) 104 } 105 func (w *lightPeerWrapper) RequestBodies([]common.Hash) error { 106 panic("RequestBodies not supported in light client mode sync") 107 } 108 func (w *lightPeerWrapper) RequestReceipts([]common.Hash) error { 109 panic("RequestReceipts not supported in light client mode sync") 110 } 111 func (w *lightPeerWrapper) RequestNodeData([]common.Hash) error { 112 panic("RequestNodeData not supported in light client mode sync") 113 } 114 115 // newPeerConnection creates a new downloader peer. 116 func newPeerConnection(id string, version int, peer Peer, logger log.Logger) *peerConnection { 117 return &peerConnection{ 118 id: id, 119 lacking: make(map[common.Hash]struct{}), 120 peer: peer, 121 version: version, 122 log: logger, 123 } 124 } 125 126 // Reset clears the internal state of a peer entity. 127 func (p *peerConnection) Reset() { 128 p.lock.Lock() 129 defer p.lock.Unlock() 130 131 atomic.StoreInt32(&p.headerIdle, 0) 132 atomic.StoreInt32(&p.blockIdle, 0) 133 atomic.StoreInt32(&p.receiptIdle, 0) 134 atomic.StoreInt32(&p.stateIdle, 0) 135 136 p.headerThroughput = 0 137 p.blockThroughput = 0 138 p.receiptThroughput = 0 139 p.stateThroughput = 0 140 141 p.lacking = make(map[common.Hash]struct{}) 142 } 143 144 // FetchHeaders sends a header retrieval request to the remote peer. 145 func (p *peerConnection) FetchHeaders(from uint64, count int) error { 146 // Short circuit if the peer is already fetching 147 if !atomic.CompareAndSwapInt32(&p.headerIdle, 0, 1) { 148 return errAlreadyFetching 149 } 150 p.headerStarted = time.Now() 151 152 // Issue the header retrieval request (absolute upwards without gaps) 153 go p.peer.RequestHeadersByNumber(from, count, 0, false) 154 155 return nil 156 } 157 158 // FetchBodies sends a block body retrieval request to the remote peer. 159 func (p *peerConnection) FetchBodies(request *fetchRequest) error { 160 // Short circuit if the peer is already fetching 161 if !atomic.CompareAndSwapInt32(&p.blockIdle, 0, 1) { 162 return errAlreadyFetching 163 } 164 p.blockStarted = time.Now() 165 166 go func() { 167 // Convert the header set to a retrievable slice 168 hashes := make([]common.Hash, 0, len(request.Headers)) 169 for _, header := range request.Headers { 170 hashes = append(hashes, header.Hash()) 171 } 172 p.peer.RequestBodies(hashes) 173 }() 174 175 return nil 176 } 177 178 // FetchReceipts sends a receipt retrieval request to the remote peer. 179 func (p *peerConnection) FetchReceipts(request *fetchRequest) error { 180 // Short circuit if the peer is already fetching 181 if !atomic.CompareAndSwapInt32(&p.receiptIdle, 0, 1) { 182 return errAlreadyFetching 183 } 184 p.receiptStarted = time.Now() 185 186 go func() { 187 // Convert the header set to a retrievable slice 188 hashes := make([]common.Hash, 0, len(request.Headers)) 189 for _, header := range request.Headers { 190 hashes = append(hashes, header.Hash()) 191 } 192 p.peer.RequestReceipts(hashes) 193 }() 194 195 return nil 196 } 197 198 // FetchNodeData sends a node state data retrieval request to the remote peer. 199 func (p *peerConnection) FetchNodeData(hashes []common.Hash) error { 200 // Short circuit if the peer is already fetching 201 if !atomic.CompareAndSwapInt32(&p.stateIdle, 0, 1) { 202 return errAlreadyFetching 203 } 204 p.stateStarted = time.Now() 205 206 go p.peer.RequestNodeData(hashes) 207 208 return nil 209 } 210 211 // SetHeadersIdle sets the peer to idle, allowing it to execute new header retrieval 212 // requests. Its estimated header retrieval throughput is updated with that measured 213 // just now. 214 func (p *peerConnection) SetHeadersIdle(delivered int, deliveryTime time.Time) { 215 p.setIdle(deliveryTime.Sub(p.headerStarted), delivered, &p.headerThroughput, &p.headerIdle) 216 } 217 218 // SetBodiesIdle sets the peer to idle, allowing it to execute block body retrieval 219 // requests. Its estimated body retrieval throughput is updated with that measured 220 // just now. 221 func (p *peerConnection) SetBodiesIdle(delivered int, deliveryTime time.Time) { 222 p.setIdle(deliveryTime.Sub(p.blockStarted), delivered, &p.blockThroughput, &p.blockIdle) 223 } 224 225 // SetReceiptsIdle sets the peer to idle, allowing it to execute new receipt 226 // retrieval requests. Its estimated receipt retrieval throughput is updated 227 // with that measured just now. 228 func (p *peerConnection) SetReceiptsIdle(delivered int, deliveryTime time.Time) { 229 p.setIdle(deliveryTime.Sub(p.receiptStarted), delivered, &p.receiptThroughput, &p.receiptIdle) 230 } 231 232 // SetNodeDataIdle sets the peer to idle, allowing it to execute new state trie 233 // data retrieval requests. Its estimated state retrieval throughput is updated 234 // with that measured just now. 235 func (p *peerConnection) SetNodeDataIdle(delivered int, deliveryTime time.Time) { 236 p.setIdle(deliveryTime.Sub(p.stateStarted), delivered, &p.stateThroughput, &p.stateIdle) 237 } 238 239 // setIdle sets the peer to idle, allowing it to execute new retrieval requests. 240 // Its estimated retrieval throughput is updated with that measured just now. 241 func (p *peerConnection) setIdle(elapsed time.Duration, delivered int, throughput *float64, idle *int32) { 242 // Irrelevant of the scaling, make sure the peer ends up idle 243 defer atomic.StoreInt32(idle, 0) 244 245 p.lock.Lock() 246 defer p.lock.Unlock() 247 248 // If nothing was delivered (hard timeout / unavailable data), reduce throughput to minimum 249 if delivered == 0 { 250 *throughput = 0 251 return 252 } 253 // Otherwise update the throughput with a new measurement 254 if elapsed <= 0 { 255 elapsed = 1 // +1 (ns) to ensure non-zero divisor 256 } 257 measured := float64(delivered) / (float64(elapsed) / float64(time.Second)) 258 259 *throughput = (1-measurementImpact)*(*throughput) + measurementImpact*measured 260 p.rtt = time.Duration((1-measurementImpact)*float64(p.rtt) + measurementImpact*float64(elapsed)) 261 262 p.log.Trace("Peer throughput measurements updated", 263 "hps", p.headerThroughput, "bps", p.blockThroughput, 264 "rps", p.receiptThroughput, "sps", p.stateThroughput, 265 "miss", len(p.lacking), "rtt", p.rtt) 266 } 267 268 // HeaderCapacity retrieves the peers header download allowance based on its 269 // previously discovered throughput. 270 func (p *peerConnection) HeaderCapacity(targetRTT time.Duration) int { 271 p.lock.RLock() 272 defer p.lock.RUnlock() 273 274 return int(math.Min(1+math.Max(1, p.headerThroughput*float64(targetRTT)/float64(time.Second)), float64(MaxHeaderFetch))) 275 } 276 277 // BlockCapacity retrieves the peers block download allowance based on its 278 // previously discovered throughput. 279 func (p *peerConnection) BlockCapacity(targetRTT time.Duration) int { 280 p.lock.RLock() 281 defer p.lock.RUnlock() 282 283 return int(math.Min(1+math.Max(1, p.blockThroughput*float64(targetRTT)/float64(time.Second)), float64(MaxBlockFetch))) 284 } 285 286 // ReceiptCapacity retrieves the peers receipt download allowance based on its 287 // previously discovered throughput. 288 func (p *peerConnection) ReceiptCapacity(targetRTT time.Duration) int { 289 p.lock.RLock() 290 defer p.lock.RUnlock() 291 292 return int(math.Min(1+math.Max(1, p.receiptThroughput*float64(targetRTT)/float64(time.Second)), float64(MaxReceiptFetch))) 293 } 294 295 // NodeDataCapacity retrieves the peers state download allowance based on its 296 // previously discovered throughput. 297 func (p *peerConnection) NodeDataCapacity(targetRTT time.Duration) int { 298 p.lock.RLock() 299 defer p.lock.RUnlock() 300 301 return int(math.Min(1+math.Max(1, p.stateThroughput*float64(targetRTT)/float64(time.Second)), float64(MaxStateFetch))) 302 } 303 304 // MarkLacking appends a new entity to the set of items (blocks, receipts, states) 305 // that a peer is known not to have (i.e. have been requested before). If the 306 // set reaches its maximum allowed capacity, items are randomly dropped off. 307 func (p *peerConnection) MarkLacking(hash common.Hash) { 308 p.lock.Lock() 309 defer p.lock.Unlock() 310 311 for len(p.lacking) >= maxLackingHashes { 312 for drop := range p.lacking { 313 delete(p.lacking, drop) 314 break 315 } 316 } 317 p.lacking[hash] = struct{}{} 318 } 319 320 // Lacks retrieves whether the hash of a blockchain item is on the peers lacking 321 // list (i.e. whether we know that the peer does not have it). 322 func (p *peerConnection) Lacks(hash common.Hash) bool { 323 p.lock.RLock() 324 defer p.lock.RUnlock() 325 326 _, ok := p.lacking[hash] 327 return ok 328 } 329 330 // peerSet represents the collection of active peer participating in the chain 331 // download procedure. 332 type peerSet struct { 333 peers map[string]*peerConnection 334 newPeerFeed event.Feed 335 peerDropFeed event.Feed 336 lock sync.RWMutex 337 } 338 339 // newPeerSet creates a new peer set top track the active download sources. 340 func newPeerSet() *peerSet { 341 return &peerSet{ 342 peers: make(map[string]*peerConnection), 343 } 344 } 345 346 // SubscribeNewPeers subscribes to peer arrival events. 347 func (ps *peerSet) SubscribeNewPeers(ch chan<- *peerConnection) event.Subscription { 348 return ps.newPeerFeed.Subscribe(ch) 349 } 350 351 // SubscribePeerDrops subscribes to peer departure events. 352 func (ps *peerSet) SubscribePeerDrops(ch chan<- *peerConnection) event.Subscription { 353 return ps.peerDropFeed.Subscribe(ch) 354 } 355 356 // Reset iterates over the current peer set, and resets each of the known peers 357 // to prepare for a next batch of block retrieval. 358 func (ps *peerSet) Reset() { 359 ps.lock.RLock() 360 defer ps.lock.RUnlock() 361 362 for _, peer := range ps.peers { 363 peer.Reset() 364 } 365 } 366 367 // Register injects a new peer into the working set, or returns an error if the 368 // peer is already known. 369 // 370 // The method also sets the starting throughput values of the new peer to the 371 // average of all existing peers, to give it a realistic chance of being used 372 // for data retrievals. 373 func (ps *peerSet) Register(p *peerConnection) error { 374 // Retrieve the current median RTT as a sane default 375 p.rtt = ps.medianRTT() 376 377 // Register the new peer with some meaningful defaults 378 ps.lock.Lock() 379 if _, ok := ps.peers[p.id]; ok { 380 ps.lock.Unlock() 381 return errAlreadyRegistered 382 } 383 if len(ps.peers) > 0 { 384 p.headerThroughput, p.blockThroughput, p.receiptThroughput, p.stateThroughput = 0, 0, 0, 0 385 386 for _, peer := range ps.peers { 387 peer.lock.RLock() 388 p.headerThroughput += peer.headerThroughput 389 p.blockThroughput += peer.blockThroughput 390 p.receiptThroughput += peer.receiptThroughput 391 p.stateThroughput += peer.stateThroughput 392 peer.lock.RUnlock() 393 } 394 p.headerThroughput /= float64(len(ps.peers)) 395 p.blockThroughput /= float64(len(ps.peers)) 396 p.receiptThroughput /= float64(len(ps.peers)) 397 p.stateThroughput /= float64(len(ps.peers)) 398 } 399 ps.peers[p.id] = p 400 ps.lock.Unlock() 401 402 ps.newPeerFeed.Send(p) 403 return nil 404 } 405 406 // Unregister removes a remote peer from the active set, disabling any further 407 // actions to/from that particular entity. 408 func (ps *peerSet) Unregister(id string) error { 409 ps.lock.Lock() 410 p, ok := ps.peers[id] 411 if !ok { 412 ps.lock.Unlock() 413 return errNotRegistered 414 } 415 delete(ps.peers, id) 416 ps.lock.Unlock() 417 418 ps.peerDropFeed.Send(p) 419 return nil 420 } 421 422 // Peer retrieves the registered peer with the given id. 423 func (ps *peerSet) Peer(id string) *peerConnection { 424 ps.lock.RLock() 425 defer ps.lock.RUnlock() 426 427 return ps.peers[id] 428 } 429 430 // Len returns if the current number of peers in the set. 431 func (ps *peerSet) Len() int { 432 ps.lock.RLock() 433 defer ps.lock.RUnlock() 434 435 return len(ps.peers) 436 } 437 438 // AllPeers retrieves a flat list of all the peers within the set. 439 func (ps *peerSet) AllPeers() []*peerConnection { 440 ps.lock.RLock() 441 defer ps.lock.RUnlock() 442 443 list := make([]*peerConnection, 0, len(ps.peers)) 444 for _, p := range ps.peers { 445 list = append(list, p) 446 } 447 return list 448 } 449 450 // HeaderIdlePeers retrieves a flat list of all the currently header-idle peers 451 // within the active peer set, ordered by their reputation. 452 func (ps *peerSet) HeaderIdlePeers() ([]*peerConnection, int) { 453 idle := func(p *peerConnection) bool { 454 return atomic.LoadInt32(&p.headerIdle) == 0 455 } 456 throughput := func(p *peerConnection) float64 { 457 p.lock.RLock() 458 defer p.lock.RUnlock() 459 return p.headerThroughput 460 } 461 return ps.idlePeers(63, 65, idle, throughput) 462 } 463 464 // BodyIdlePeers retrieves a flat list of all the currently body-idle peers within 465 // the active peer set, ordered by their reputation. 466 func (ps *peerSet) BodyIdlePeers() ([]*peerConnection, int) { 467 idle := func(p *peerConnection) bool { 468 return atomic.LoadInt32(&p.blockIdle) == 0 469 } 470 throughput := func(p *peerConnection) float64 { 471 p.lock.RLock() 472 defer p.lock.RUnlock() 473 return p.blockThroughput 474 } 475 return ps.idlePeers(63, 65, idle, throughput) 476 } 477 478 // ReceiptIdlePeers retrieves a flat list of all the currently receipt-idle peers 479 // within the active peer set, ordered by their reputation. 480 func (ps *peerSet) ReceiptIdlePeers() ([]*peerConnection, int) { 481 idle := func(p *peerConnection) bool { 482 return atomic.LoadInt32(&p.receiptIdle) == 0 483 } 484 throughput := func(p *peerConnection) float64 { 485 p.lock.RLock() 486 defer p.lock.RUnlock() 487 return p.receiptThroughput 488 } 489 return ps.idlePeers(63, 65, idle, throughput) 490 } 491 492 // NodeDataIdlePeers retrieves a flat list of all the currently node-data-idle 493 // peers within the active peer set, ordered by their reputation. 494 func (ps *peerSet) NodeDataIdlePeers() ([]*peerConnection, int) { 495 idle := func(p *peerConnection) bool { 496 return atomic.LoadInt32(&p.stateIdle) == 0 497 } 498 throughput := func(p *peerConnection) float64 { 499 p.lock.RLock() 500 defer p.lock.RUnlock() 501 return p.stateThroughput 502 } 503 return ps.idlePeers(63, 65, idle, throughput) 504 } 505 506 // idlePeers retrieves a flat list of all currently idle peers satisfying the 507 // protocol version constraints, using the provided function to check idleness. 508 // The resulting set of peers are sorted by their measure throughput. 509 func (ps *peerSet) idlePeers(minProtocol, maxProtocol int, idleCheck func(*peerConnection) bool, throughput func(*peerConnection) float64) ([]*peerConnection, int) { 510 ps.lock.RLock() 511 defer ps.lock.RUnlock() 512 513 idle, total := make([]*peerConnection, 0, len(ps.peers)), 0 514 tps := make([]float64, 0, len(ps.peers)) 515 for _, p := range ps.peers { 516 if p.version >= minProtocol && p.version <= maxProtocol || p.version == consensus.Istanbul99 { 517 if idleCheck(p) { 518 idle = append(idle, p) 519 tps = append(tps, throughput(p)) 520 } 521 total++ 522 } 523 } 524 // And sort them 525 sortPeers := &peerThroughputSort{idle, tps} 526 sort.Sort(sortPeers) 527 return sortPeers.p, total 528 } 529 530 // medianRTT returns the median RTT of the peerset, considering only the tuning 531 // peers if there are more peers available. 532 func (ps *peerSet) medianRTT() time.Duration { 533 // Gather all the currently measured round trip times 534 ps.lock.RLock() 535 defer ps.lock.RUnlock() 536 537 rtts := make([]float64, 0, len(ps.peers)) 538 for _, p := range ps.peers { 539 p.lock.RLock() 540 rtts = append(rtts, float64(p.rtt)) 541 p.lock.RUnlock() 542 } 543 sort.Float64s(rtts) 544 545 median := rttMaxEstimate 546 if qosTuningPeers <= len(rtts) { 547 median = time.Duration(rtts[qosTuningPeers/2]) // Median of our tuning peers 548 } else if len(rtts) > 0 { 549 median = time.Duration(rtts[len(rtts)/2]) // Median of our connected peers (maintain even like this some baseline qos) 550 } 551 // Restrict the RTT into some QoS defaults, irrelevant of true RTT 552 if median < rttMinEstimate { 553 median = rttMinEstimate 554 } 555 if median > rttMaxEstimate { 556 median = rttMaxEstimate 557 } 558 return median 559 } 560 561 // peerThroughputSort implements the Sort interface, and allows for 562 // sorting a set of peers by their throughput 563 // The sorted data is with the _highest_ throughput first 564 type peerThroughputSort struct { 565 p []*peerConnection 566 tp []float64 567 } 568 569 func (ps *peerThroughputSort) Len() int { 570 return len(ps.p) 571 } 572 573 func (ps *peerThroughputSort) Less(i, j int) bool { 574 return ps.tp[i] > ps.tp[j] 575 } 576 577 func (ps *peerThroughputSort) Swap(i, j int) { 578 ps.p[i], ps.p[j] = ps.p[j], ps.p[i] 579 ps.tp[i], ps.tp[j] = ps.tp[j], ps.tp[i] 580 }