peer.go 19 KB

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