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