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