peer.go 19 KB

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