peer.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  1. // Copyright 2016 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. package les
  17. import (
  18. "errors"
  19. "fmt"
  20. "math/big"
  21. "math/rand"
  22. "net"
  23. "sync"
  24. "sync/atomic"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/common/mclock"
  28. "github.com/ethereum/go-ethereum/core"
  29. "github.com/ethereum/go-ethereum/core/forkid"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/les/flowcontrol"
  32. "github.com/ethereum/go-ethereum/les/utils"
  33. vfc "github.com/ethereum/go-ethereum/les/vflux/client"
  34. vfs "github.com/ethereum/go-ethereum/les/vflux/server"
  35. "github.com/ethereum/go-ethereum/light"
  36. "github.com/ethereum/go-ethereum/p2p"
  37. "github.com/ethereum/go-ethereum/params"
  38. "github.com/ethereum/go-ethereum/rlp"
  39. )
  40. var (
  41. errClosed = errors.New("peer set is closed")
  42. errAlreadyRegistered = errors.New("peer is already registered")
  43. errNotRegistered = errors.New("peer is not registered")
  44. )
  45. const (
  46. maxRequestErrors = 20 // number of invalid requests tolerated (makes the protocol less brittle but still avoids spam)
  47. maxResponseErrors = 50 // number of invalid responses tolerated (makes the protocol less brittle but still avoids spam)
  48. allowedUpdateBytes = 100000 // initial/maximum allowed update size
  49. allowedUpdateRate = time.Millisecond * 10 // time constant for recharging one byte of allowance
  50. freezeTimeBase = time.Millisecond * 700 // fixed component of client freeze time
  51. freezeTimeRandom = time.Millisecond * 600 // random component of client freeze time
  52. freezeCheckPeriod = time.Millisecond * 100 // buffer value recheck period after initial freeze time has elapsed
  53. // If the total encoded size of a sent transaction batch is over txSizeCostLimit
  54. // per transaction then the request cost is calculated as proportional to the
  55. // encoded size instead of the transaction count
  56. txSizeCostLimit = 0x4000
  57. // handshakeTimeout is the timeout LES handshake will be treated as failed.
  58. handshakeTimeout = 5 * time.Second
  59. )
  60. const (
  61. announceTypeNone = iota
  62. announceTypeSimple
  63. announceTypeSigned
  64. )
  65. type keyValueEntry struct {
  66. Key string
  67. Value rlp.RawValue
  68. }
  69. type keyValueList []keyValueEntry
  70. type keyValueMap map[string]rlp.RawValue
  71. func (l keyValueList) add(key string, val interface{}) keyValueList {
  72. var entry keyValueEntry
  73. entry.Key = key
  74. if val == nil {
  75. val = uint64(0)
  76. }
  77. enc, err := rlp.EncodeToBytes(val)
  78. if err == nil {
  79. entry.Value = enc
  80. }
  81. return append(l, entry)
  82. }
  83. func (l keyValueList) decode() (keyValueMap, uint64) {
  84. m := make(keyValueMap)
  85. var size uint64
  86. for _, entry := range l {
  87. m[entry.Key] = entry.Value
  88. size += uint64(len(entry.Key)) + uint64(len(entry.Value)) + 8
  89. }
  90. return m, size
  91. }
  92. func (m keyValueMap) get(key string, val interface{}) error {
  93. enc, ok := m[key]
  94. if !ok {
  95. return errResp(ErrMissingKey, "%s", key)
  96. }
  97. if val == nil {
  98. return nil
  99. }
  100. return rlp.DecodeBytes(enc, val)
  101. }
  102. // peerCommons contains fields needed by both server peer and client peer.
  103. type peerCommons struct {
  104. *p2p.Peer
  105. rw p2p.MsgReadWriter
  106. id string // Peer identity.
  107. version int // Protocol version negotiated.
  108. network uint64 // Network ID being on.
  109. frozen uint32 // Flag whether the peer is frozen.
  110. announceType uint64 // New block announcement type.
  111. serving uint32 // The status indicates the peer is served.
  112. headInfo blockInfo // Last announced block information.
  113. // Background task queue for caching peer tasks and executing in order.
  114. sendQueue *utils.ExecQueue
  115. // Flow control agreement.
  116. fcParams flowcontrol.ServerParams // The config for token bucket.
  117. fcCosts requestCostTable // The Maximum request cost table.
  118. closeCh chan struct{}
  119. lock sync.RWMutex // Lock used to protect all thread-sensitive fields.
  120. }
  121. // isFrozen returns true if the client is frozen or the server has put our
  122. // client in frozen state
  123. func (p *peerCommons) isFrozen() bool {
  124. return atomic.LoadUint32(&p.frozen) != 0
  125. }
  126. // canQueue returns an indicator whether the peer can queue an operation.
  127. func (p *peerCommons) canQueue() bool {
  128. return p.sendQueue.CanQueue() && !p.isFrozen()
  129. }
  130. // queueSend caches a peer operation in the background task queue.
  131. // Please ensure to check `canQueue` before call this function
  132. func (p *peerCommons) queueSend(f func()) bool {
  133. return p.sendQueue.Queue(f)
  134. }
  135. // String implements fmt.Stringer.
  136. func (p *peerCommons) String() string {
  137. return fmt.Sprintf("Peer %s [%s]", p.id, fmt.Sprintf("les/%d", p.version))
  138. }
  139. // PeerInfo represents a short summary of the `eth` sub-protocol metadata known
  140. // about a connected peer.
  141. type PeerInfo struct {
  142. Version int `json:"version"` // Ethereum protocol version negotiated
  143. Difficulty *big.Int `json:"difficulty"` // Total difficulty of the peer's blockchain
  144. Head string `json:"head"` // SHA3 hash of the peer's best owned block
  145. }
  146. // Info gathers and returns a collection of metadata known about a peer.
  147. func (p *peerCommons) Info() *PeerInfo {
  148. return &PeerInfo{
  149. Version: p.version,
  150. Difficulty: p.Td(),
  151. Head: fmt.Sprintf("%x", p.Head()),
  152. }
  153. }
  154. // Head retrieves a copy of the current head (most recent) hash of the peer.
  155. func (p *peerCommons) Head() (hash common.Hash) {
  156. p.lock.RLock()
  157. defer p.lock.RUnlock()
  158. return p.headInfo.Hash
  159. }
  160. // Td retrieves the current total difficulty of a peer.
  161. func (p *peerCommons) Td() *big.Int {
  162. p.lock.RLock()
  163. defer p.lock.RUnlock()
  164. return new(big.Int).Set(p.headInfo.Td)
  165. }
  166. // HeadAndTd retrieves the current head hash and total difficulty of a peer.
  167. func (p *peerCommons) HeadAndTd() (hash common.Hash, td *big.Int) {
  168. p.lock.RLock()
  169. defer p.lock.RUnlock()
  170. return p.headInfo.Hash, new(big.Int).Set(p.headInfo.Td)
  171. }
  172. // sendReceiveHandshake exchanges handshake packet with remote peer and returns any error
  173. // if failed to send or receive packet.
  174. func (p *peerCommons) sendReceiveHandshake(sendList keyValueList) (keyValueList, error) {
  175. var (
  176. errc = make(chan error, 2)
  177. recvList keyValueList
  178. )
  179. // Send out own handshake in a new thread
  180. go func() {
  181. errc <- p2p.Send(p.rw, StatusMsg, sendList)
  182. }()
  183. go func() {
  184. // In the mean time retrieve the remote status message
  185. msg, err := p.rw.ReadMsg()
  186. if err != nil {
  187. errc <- err
  188. return
  189. }
  190. if msg.Code != StatusMsg {
  191. errc <- errResp(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Code, StatusMsg)
  192. return
  193. }
  194. if msg.Size > ProtocolMaxMsgSize {
  195. errc <- errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  196. return
  197. }
  198. // Decode the handshake
  199. if err := msg.Decode(&recvList); err != nil {
  200. errc <- errResp(ErrDecode, "msg %v: %v", msg, err)
  201. return
  202. }
  203. errc <- nil
  204. }()
  205. timeout := time.NewTimer(handshakeTimeout)
  206. defer timeout.Stop()
  207. for i := 0; i < 2; i++ {
  208. select {
  209. case err := <-errc:
  210. if err != nil {
  211. return nil, err
  212. }
  213. case <-timeout.C:
  214. return nil, p2p.DiscReadTimeout
  215. }
  216. }
  217. return recvList, nil
  218. }
  219. // handshake executes the les protocol handshake, negotiating version number,
  220. // network IDs, difficulties, head and genesis blocks. Besides the basic handshake
  221. // fields, server and client can exchange and resolve some specified fields through
  222. // two callback functions.
  223. func (p *peerCommons) handshake(td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, forkID forkid.ID, forkFilter forkid.Filter, sendCallback func(*keyValueList), recvCallback func(keyValueMap) error) error {
  224. p.lock.Lock()
  225. defer p.lock.Unlock()
  226. var send keyValueList
  227. // Add some basic handshake fields
  228. send = send.add("protocolVersion", uint64(p.version))
  229. send = send.add("networkId", p.network)
  230. // Note: the head info announced at handshake is only used in case of server peers
  231. // but dummy values are still announced by clients for compatibility with older servers
  232. send = send.add("headTd", td)
  233. send = send.add("headHash", head)
  234. send = send.add("headNum", headNum)
  235. send = send.add("genesisHash", genesis)
  236. // If the protocol version is beyond les4, then pass the forkID
  237. // as well. Check http://eips.ethereum.org/EIPS/eip-2124 for more
  238. // spec detail.
  239. if p.version >= lpv4 {
  240. send = send.add("forkID", forkID)
  241. }
  242. // Add client-specified or server-specified fields
  243. if sendCallback != nil {
  244. sendCallback(&send)
  245. }
  246. // Exchange the handshake packet and resolve the received one.
  247. recvList, err := p.sendReceiveHandshake(send)
  248. if err != nil {
  249. return err
  250. }
  251. recv, size := recvList.decode()
  252. if size > allowedUpdateBytes {
  253. return errResp(ErrRequestRejected, "")
  254. }
  255. var rGenesis common.Hash
  256. var rVersion, rNetwork uint64
  257. if err := recv.get("protocolVersion", &rVersion); err != nil {
  258. return err
  259. }
  260. if err := recv.get("networkId", &rNetwork); err != nil {
  261. return err
  262. }
  263. if err := recv.get("genesisHash", &rGenesis); err != nil {
  264. return err
  265. }
  266. if rGenesis != genesis {
  267. return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", rGenesis[:8], genesis[:8])
  268. }
  269. if rNetwork != p.network {
  270. return errResp(ErrNetworkIdMismatch, "%d (!= %d)", rNetwork, p.network)
  271. }
  272. if int(rVersion) != p.version {
  273. return errResp(ErrProtocolVersionMismatch, "%d (!= %d)", rVersion, p.version)
  274. }
  275. // Check forkID if the protocol version is beyond the les4
  276. if p.version >= lpv4 {
  277. var forkID forkid.ID
  278. if err := recv.get("forkID", &forkID); err != nil {
  279. return err
  280. }
  281. if err := forkFilter(forkID); err != nil {
  282. return errResp(ErrForkIDRejected, "%v", err)
  283. }
  284. }
  285. if recvCallback != nil {
  286. return recvCallback(recv)
  287. }
  288. return nil
  289. }
  290. // close closes the channel and notifies all background routines to exit.
  291. func (p *peerCommons) close() {
  292. close(p.closeCh)
  293. p.sendQueue.Quit()
  294. }
  295. // serverPeer represents each node to which the client is connected.
  296. // The node here refers to the les server.
  297. type serverPeer struct {
  298. peerCommons
  299. // Status fields
  300. trusted bool // The flag whether the server is selected as trusted server.
  301. onlyAnnounce bool // The flag whether the server sends announcement only.
  302. chainSince, chainRecent uint64 // The range of chain server peer can serve.
  303. stateSince, stateRecent uint64 // The range of state server peer can serve.
  304. txHistory uint64 // The length of available tx history, 0 means all, 1 means disabled
  305. // Advertised checkpoint fields
  306. checkpointNumber uint64 // The block height which the checkpoint is registered.
  307. checkpoint params.TrustedCheckpoint // The advertised checkpoint sent by server.
  308. fcServer *flowcontrol.ServerNode // Client side mirror token bucket.
  309. vtLock sync.Mutex
  310. nodeValueTracker *vfc.NodeValueTracker
  311. sentReqs map[uint64]sentReqEntry
  312. // Statistics
  313. errCount utils.LinearExpiredValue // Counter the invalid responses server has replied
  314. updateCount uint64
  315. updateTime mclock.AbsTime
  316. // Test callback hooks
  317. hasBlockHook func(common.Hash, uint64, bool) bool // Used to determine whether the server has the specified block.
  318. }
  319. func newServerPeer(version int, network uint64, trusted bool, p *p2p.Peer, rw p2p.MsgReadWriter) *serverPeer {
  320. return &serverPeer{
  321. peerCommons: peerCommons{
  322. Peer: p,
  323. rw: rw,
  324. id: p.ID().String(),
  325. version: version,
  326. network: network,
  327. sendQueue: utils.NewExecQueue(100),
  328. closeCh: make(chan struct{}),
  329. },
  330. trusted: trusted,
  331. errCount: utils.LinearExpiredValue{Rate: mclock.AbsTime(time.Hour)},
  332. }
  333. }
  334. // rejectUpdate returns true if a parameter update has to be rejected because
  335. // the size and/or rate of updates exceed the capacity limitation
  336. func (p *serverPeer) rejectUpdate(size uint64) bool {
  337. now := mclock.Now()
  338. if p.updateCount == 0 {
  339. p.updateTime = now
  340. } else {
  341. dt := now - p.updateTime
  342. p.updateTime = now
  343. r := uint64(dt / mclock.AbsTime(allowedUpdateRate))
  344. if p.updateCount > r {
  345. p.updateCount -= r
  346. } else {
  347. p.updateCount = 0
  348. }
  349. }
  350. p.updateCount += size
  351. return p.updateCount > allowedUpdateBytes
  352. }
  353. // freeze processes Stop messages from the given server and set the status as
  354. // frozen.
  355. func (p *serverPeer) freeze() {
  356. if atomic.CompareAndSwapUint32(&p.frozen, 0, 1) {
  357. p.sendQueue.Clear()
  358. }
  359. }
  360. // unfreeze processes Resume messages from the given server and set the status
  361. // as unfrozen.
  362. func (p *serverPeer) unfreeze() {
  363. atomic.StoreUint32(&p.frozen, 0)
  364. }
  365. // sendRequest send a request to the server based on the given message type
  366. // and content.
  367. func sendRequest(w p2p.MsgWriter, msgcode, reqID uint64, data interface{}) error {
  368. type req struct {
  369. ReqID uint64
  370. Data interface{}
  371. }
  372. return p2p.Send(w, msgcode, req{reqID, data})
  373. }
  374. func (p *serverPeer) sendRequest(msgcode, reqID uint64, data interface{}, amount int) error {
  375. p.sentRequest(reqID, uint32(msgcode), uint32(amount))
  376. return sendRequest(p.rw, msgcode, reqID, data)
  377. }
  378. // requestHeadersByHash fetches a batch of blocks' headers corresponding to the
  379. // specified header query, based on the hash of an origin block.
  380. func (p *serverPeer) requestHeadersByHash(reqID uint64, origin common.Hash, amount int, skip int, reverse bool) error {
  381. p.Log().Debug("Fetching batch of headers", "count", amount, "fromhash", origin, "skip", skip, "reverse", reverse)
  382. return p.sendRequest(GetBlockHeadersMsg, reqID, &GetBlockHeadersData{Origin: hashOrNumber{Hash: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse}, amount)
  383. }
  384. // requestHeadersByNumber fetches a batch of blocks' headers corresponding to the
  385. // specified header query, based on the number of an origin block.
  386. func (p *serverPeer) requestHeadersByNumber(reqID, origin uint64, amount int, skip int, reverse bool) error {
  387. p.Log().Debug("Fetching batch of headers", "count", amount, "fromnum", origin, "skip", skip, "reverse", reverse)
  388. return p.sendRequest(GetBlockHeadersMsg, reqID, &GetBlockHeadersData{Origin: hashOrNumber{Number: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse}, amount)
  389. }
  390. // requestBodies fetches a batch of blocks' bodies corresponding to the hashes
  391. // specified.
  392. func (p *serverPeer) requestBodies(reqID uint64, hashes []common.Hash) error {
  393. p.Log().Debug("Fetching batch of block bodies", "count", len(hashes))
  394. return p.sendRequest(GetBlockBodiesMsg, reqID, hashes, len(hashes))
  395. }
  396. // requestCode fetches a batch of arbitrary data from a node's known state
  397. // data, corresponding to the specified hashes.
  398. func (p *serverPeer) requestCode(reqID uint64, reqs []CodeReq) error {
  399. p.Log().Debug("Fetching batch of codes", "count", len(reqs))
  400. return p.sendRequest(GetCodeMsg, reqID, reqs, len(reqs))
  401. }
  402. // requestReceipts fetches a batch of transaction receipts from a remote node.
  403. func (p *serverPeer) requestReceipts(reqID uint64, hashes []common.Hash) error {
  404. p.Log().Debug("Fetching batch of receipts", "count", len(hashes))
  405. return p.sendRequest(GetReceiptsMsg, reqID, hashes, len(hashes))
  406. }
  407. // requestProofs fetches a batch of merkle proofs from a remote node.
  408. func (p *serverPeer) requestProofs(reqID uint64, reqs []ProofReq) error {
  409. p.Log().Debug("Fetching batch of proofs", "count", len(reqs))
  410. return p.sendRequest(GetProofsV2Msg, reqID, reqs, len(reqs))
  411. }
  412. // requestHelperTrieProofs fetches a batch of HelperTrie merkle proofs from a remote node.
  413. func (p *serverPeer) requestHelperTrieProofs(reqID uint64, reqs []HelperTrieReq) error {
  414. p.Log().Debug("Fetching batch of HelperTrie proofs", "count", len(reqs))
  415. return p.sendRequest(GetHelperTrieProofsMsg, reqID, reqs, len(reqs))
  416. }
  417. // requestTxStatus fetches a batch of transaction status records from a remote node.
  418. func (p *serverPeer) requestTxStatus(reqID uint64, txHashes []common.Hash) error {
  419. p.Log().Debug("Requesting transaction status", "count", len(txHashes))
  420. return p.sendRequest(GetTxStatusMsg, reqID, txHashes, len(txHashes))
  421. }
  422. // sendTxs creates a reply with a batch of transactions to be added to the remote transaction pool.
  423. func (p *serverPeer) sendTxs(reqID uint64, amount int, txs rlp.RawValue) error {
  424. p.Log().Debug("Sending batch of transactions", "amount", amount, "size", len(txs))
  425. sizeFactor := (len(txs) + txSizeCostLimit/2) / txSizeCostLimit
  426. if sizeFactor > amount {
  427. amount = sizeFactor
  428. }
  429. return p.sendRequest(SendTxV2Msg, reqID, txs, amount)
  430. }
  431. // waitBefore implements distPeer interface
  432. func (p *serverPeer) waitBefore(maxCost uint64) (time.Duration, float64) {
  433. return p.fcServer.CanSend(maxCost)
  434. }
  435. // getRequestCost returns an estimated request cost according to the flow control
  436. // rules negotiated between the server and the client.
  437. func (p *serverPeer) getRequestCost(msgcode uint64, amount int) uint64 {
  438. p.lock.RLock()
  439. defer p.lock.RUnlock()
  440. costs := p.fcCosts[msgcode]
  441. if costs == nil {
  442. return 0
  443. }
  444. cost := costs.baseCost + costs.reqCost*uint64(amount)
  445. if cost > p.fcParams.BufLimit {
  446. cost = p.fcParams.BufLimit
  447. }
  448. return cost
  449. }
  450. // getTxRelayCost returns an estimated relay cost according to the flow control
  451. // rules negotiated between the server and the client.
  452. func (p *serverPeer) getTxRelayCost(amount, size int) uint64 {
  453. p.lock.RLock()
  454. defer p.lock.RUnlock()
  455. costs := p.fcCosts[SendTxV2Msg]
  456. if costs == nil {
  457. return 0
  458. }
  459. cost := costs.baseCost + costs.reqCost*uint64(amount)
  460. sizeCost := costs.baseCost + costs.reqCost*uint64(size)/txSizeCostLimit
  461. if sizeCost > cost {
  462. cost = sizeCost
  463. }
  464. if cost > p.fcParams.BufLimit {
  465. cost = p.fcParams.BufLimit
  466. }
  467. return cost
  468. }
  469. // HasBlock checks if the peer has a given block
  470. func (p *serverPeer) HasBlock(hash common.Hash, number uint64, hasState bool) bool {
  471. p.lock.RLock()
  472. defer p.lock.RUnlock()
  473. if p.hasBlockHook != nil {
  474. return p.hasBlockHook(hash, number, hasState)
  475. }
  476. head := p.headInfo.Number
  477. var since, recent uint64
  478. if hasState {
  479. since = p.stateSince
  480. recent = p.stateRecent
  481. } else {
  482. since = p.chainSince
  483. recent = p.chainRecent
  484. }
  485. return head >= number && number >= since && (recent == 0 || number+recent+4 > head)
  486. }
  487. // updateFlowControl updates the flow control parameters belonging to the server
  488. // node if the announced key/value set contains relevant fields
  489. func (p *serverPeer) updateFlowControl(update keyValueMap) {
  490. p.lock.Lock()
  491. defer p.lock.Unlock()
  492. // If any of the flow control params is nil, refuse to update.
  493. var params flowcontrol.ServerParams
  494. if update.get("flowControl/BL", &params.BufLimit) == nil && update.get("flowControl/MRR", &params.MinRecharge) == nil {
  495. // todo can light client set a minimal acceptable flow control params?
  496. p.fcParams = params
  497. p.fcServer.UpdateParams(params)
  498. }
  499. var MRC RequestCostList
  500. if update.get("flowControl/MRC", &MRC) == nil {
  501. costUpdate := MRC.decode(ProtocolLengths[uint(p.version)])
  502. for code, cost := range costUpdate {
  503. p.fcCosts[code] = cost
  504. }
  505. }
  506. }
  507. // updateHead updates the head information based on the announcement from
  508. // the peer.
  509. func (p *serverPeer) updateHead(hash common.Hash, number uint64, td *big.Int) {
  510. p.lock.Lock()
  511. defer p.lock.Unlock()
  512. p.headInfo = blockInfo{Hash: hash, Number: number, Td: td}
  513. }
  514. // Handshake executes the les protocol handshake, negotiating version number,
  515. // network IDs and genesis blocks.
  516. func (p *serverPeer) Handshake(genesis common.Hash, forkid forkid.ID, forkFilter forkid.Filter) error {
  517. // Note: there is no need to share local head with a server but older servers still
  518. // require these fields so we announce zero values.
  519. return p.handshake(common.Big0, common.Hash{}, 0, genesis, forkid, forkFilter, func(lists *keyValueList) {
  520. // Add some client-specific handshake fields
  521. //
  522. // Enable signed announcement randomly even the server is not trusted.
  523. p.announceType = announceTypeSimple
  524. if p.trusted {
  525. p.announceType = announceTypeSigned
  526. }
  527. *lists = (*lists).add("announceType", p.announceType)
  528. }, func(recv keyValueMap) error {
  529. var (
  530. rHash common.Hash
  531. rNum uint64
  532. rTd *big.Int
  533. )
  534. if err := recv.get("headTd", &rTd); err != nil {
  535. return err
  536. }
  537. if err := recv.get("headHash", &rHash); err != nil {
  538. return err
  539. }
  540. if err := recv.get("headNum", &rNum); err != nil {
  541. return err
  542. }
  543. p.headInfo = blockInfo{Hash: rHash, Number: rNum, Td: rTd}
  544. if recv.get("serveChainSince", &p.chainSince) != nil {
  545. p.onlyAnnounce = true
  546. }
  547. if recv.get("serveRecentChain", &p.chainRecent) != nil {
  548. p.chainRecent = 0
  549. }
  550. if recv.get("serveStateSince", &p.stateSince) != nil {
  551. p.onlyAnnounce = true
  552. }
  553. if recv.get("serveRecentState", &p.stateRecent) != nil {
  554. p.stateRecent = 0
  555. }
  556. if recv.get("txRelay", nil) != nil {
  557. p.onlyAnnounce = true
  558. }
  559. if p.version >= lpv4 {
  560. var recentTx uint
  561. if err := recv.get("recentTxLookup", &recentTx); err != nil {
  562. return err
  563. }
  564. p.txHistory = uint64(recentTx)
  565. } else {
  566. // The weak assumption is held here that legacy les server(les2,3)
  567. // has unlimited transaction history. The les serving in these legacy
  568. // versions is disabled if the transaction is unindexed.
  569. p.txHistory = txIndexUnlimited
  570. }
  571. if p.onlyAnnounce && !p.trusted {
  572. return errResp(ErrUselessPeer, "peer cannot serve requests")
  573. }
  574. // Parse flow control handshake packet.
  575. var sParams flowcontrol.ServerParams
  576. if err := recv.get("flowControl/BL", &sParams.BufLimit); err != nil {
  577. return err
  578. }
  579. if err := recv.get("flowControl/MRR", &sParams.MinRecharge); err != nil {
  580. return err
  581. }
  582. var MRC RequestCostList
  583. if err := recv.get("flowControl/MRC", &MRC); err != nil {
  584. return err
  585. }
  586. p.fcParams = sParams
  587. p.fcServer = flowcontrol.NewServerNode(sParams, &mclock.System{})
  588. p.fcCosts = MRC.decode(ProtocolLengths[uint(p.version)])
  589. recv.get("checkpoint/value", &p.checkpoint)
  590. recv.get("checkpoint/registerHeight", &p.checkpointNumber)
  591. if !p.onlyAnnounce {
  592. for msgCode := range reqAvgTimeCost {
  593. if p.fcCosts[msgCode] == nil {
  594. return errResp(ErrUselessPeer, "peer does not support message %d", msgCode)
  595. }
  596. }
  597. }
  598. return nil
  599. })
  600. }
  601. // setValueTracker sets the value tracker references for connected servers. Note that the
  602. // references should be removed upon disconnection by setValueTracker(nil, nil).
  603. func (p *serverPeer) setValueTracker(nvt *vfc.NodeValueTracker) {
  604. p.vtLock.Lock()
  605. p.nodeValueTracker = nvt
  606. if nvt != nil {
  607. p.sentReqs = make(map[uint64]sentReqEntry)
  608. } else {
  609. p.sentReqs = nil
  610. }
  611. p.vtLock.Unlock()
  612. }
  613. // updateVtParams updates the server's price table in the value tracker.
  614. func (p *serverPeer) updateVtParams() {
  615. p.vtLock.Lock()
  616. defer p.vtLock.Unlock()
  617. if p.nodeValueTracker == nil {
  618. return
  619. }
  620. reqCosts := make([]uint64, len(requestList))
  621. for code, costs := range p.fcCosts {
  622. if m, ok := requestMapping[uint32(code)]; ok {
  623. reqCosts[m.first] = costs.baseCost + costs.reqCost
  624. if m.rest != -1 {
  625. reqCosts[m.rest] = costs.reqCost
  626. }
  627. }
  628. }
  629. p.nodeValueTracker.UpdateCosts(reqCosts)
  630. }
  631. // sentReqEntry remembers sent requests and their sending times
  632. type sentReqEntry struct {
  633. reqType, amount uint32
  634. at mclock.AbsTime
  635. }
  636. // sentRequest marks a request sent at the current moment to this server.
  637. func (p *serverPeer) sentRequest(id uint64, reqType, amount uint32) {
  638. p.vtLock.Lock()
  639. if p.sentReqs != nil {
  640. p.sentReqs[id] = sentReqEntry{reqType, amount, mclock.Now()}
  641. }
  642. p.vtLock.Unlock()
  643. }
  644. // answeredRequest marks a request answered at the current moment by this server.
  645. func (p *serverPeer) answeredRequest(id uint64) {
  646. p.vtLock.Lock()
  647. if p.sentReqs == nil {
  648. p.vtLock.Unlock()
  649. return
  650. }
  651. e, ok := p.sentReqs[id]
  652. delete(p.sentReqs, id)
  653. nvt := p.nodeValueTracker
  654. p.vtLock.Unlock()
  655. if !ok {
  656. return
  657. }
  658. var (
  659. vtReqs [2]vfc.ServedRequest
  660. reqCount int
  661. )
  662. m := requestMapping[e.reqType]
  663. if m.rest == -1 || e.amount <= 1 {
  664. reqCount = 1
  665. vtReqs[0] = vfc.ServedRequest{ReqType: uint32(m.first), Amount: e.amount}
  666. } else {
  667. reqCount = 2
  668. vtReqs[0] = vfc.ServedRequest{ReqType: uint32(m.first), Amount: 1}
  669. vtReqs[1] = vfc.ServedRequest{ReqType: uint32(m.rest), Amount: e.amount - 1}
  670. }
  671. dt := time.Duration(mclock.Now() - e.at)
  672. nvt.Served(vtReqs[:reqCount], dt)
  673. }
  674. // clientPeer represents each node to which the les server is connected.
  675. // The node here refers to the light client.
  676. type clientPeer struct {
  677. peerCommons
  678. // responseLock ensures that responses are queued in the same order as
  679. // RequestProcessed is called
  680. responseLock sync.Mutex
  681. responseCount uint64 // Counter to generate an unique id for request processing.
  682. balance *vfs.NodeBalance
  683. // invalidLock is used for protecting invalidCount.
  684. invalidLock sync.RWMutex
  685. invalidCount utils.LinearExpiredValue // Counter the invalid request the client peer has made.
  686. server bool
  687. errCh chan error
  688. fcClient *flowcontrol.ClientNode // Server side mirror token bucket.
  689. }
  690. func newClientPeer(version int, network uint64, p *p2p.Peer, rw p2p.MsgReadWriter) *clientPeer {
  691. return &clientPeer{
  692. peerCommons: peerCommons{
  693. Peer: p,
  694. rw: rw,
  695. id: p.ID().String(),
  696. version: version,
  697. network: network,
  698. sendQueue: utils.NewExecQueue(100),
  699. closeCh: make(chan struct{}),
  700. },
  701. invalidCount: utils.LinearExpiredValue{Rate: mclock.AbsTime(time.Hour)},
  702. errCh: make(chan error, 1),
  703. }
  704. }
  705. // freeClientId returns a string identifier for the peer. Multiple peers with
  706. // the same identifier can not be connected in free mode simultaneously.
  707. func (p *clientPeer) freeClientId() string {
  708. if addr, ok := p.RemoteAddr().(*net.TCPAddr); ok {
  709. if addr.IP.IsLoopback() {
  710. // using peer id instead of loopback ip address allows multiple free
  711. // connections from local machine to own server
  712. return p.id
  713. } else {
  714. return addr.IP.String()
  715. }
  716. }
  717. return p.id
  718. }
  719. // sendStop notifies the client about being in frozen state
  720. func (p *clientPeer) sendStop() error {
  721. return p2p.Send(p.rw, StopMsg, struct{}{})
  722. }
  723. // sendResume notifies the client about getting out of frozen state
  724. func (p *clientPeer) sendResume(bv uint64) error {
  725. return p2p.Send(p.rw, ResumeMsg, bv)
  726. }
  727. // freeze temporarily puts the client in a frozen state which means all unprocessed
  728. // and subsequent requests are dropped. Unfreezing happens automatically after a short
  729. // time if the client's buffer value is at least in the slightly positive region.
  730. // The client is also notified about being frozen/unfrozen with a Stop/Resume message.
  731. func (p *clientPeer) freeze() {
  732. if p.version < lpv3 {
  733. // if Stop/Resume is not supported then just drop the peer after setting
  734. // its frozen status permanently
  735. atomic.StoreUint32(&p.frozen, 1)
  736. p.Peer.Disconnect(p2p.DiscUselessPeer)
  737. return
  738. }
  739. if atomic.SwapUint32(&p.frozen, 1) == 0 {
  740. go func() {
  741. p.sendStop()
  742. time.Sleep(freezeTimeBase + time.Duration(rand.Int63n(int64(freezeTimeRandom))))
  743. for {
  744. bufValue, bufLimit := p.fcClient.BufferStatus()
  745. if bufLimit == 0 {
  746. return
  747. }
  748. if bufValue <= bufLimit/8 {
  749. time.Sleep(freezeCheckPeriod)
  750. continue
  751. }
  752. atomic.StoreUint32(&p.frozen, 0)
  753. p.sendResume(bufValue)
  754. return
  755. }
  756. }()
  757. }
  758. }
  759. // reply struct represents a reply with the actual data already RLP encoded and
  760. // only the bv (buffer value) missing. This allows the serving mechanism to
  761. // calculate the bv value which depends on the data size before sending the reply.
  762. type reply struct {
  763. w p2p.MsgWriter
  764. msgcode, reqID uint64
  765. data rlp.RawValue
  766. }
  767. // send sends the reply with the calculated buffer value
  768. func (r *reply) send(bv uint64) error {
  769. type resp struct {
  770. ReqID, BV uint64
  771. Data rlp.RawValue
  772. }
  773. return p2p.Send(r.w, r.msgcode, resp{r.reqID, bv, r.data})
  774. }
  775. // size returns the RLP encoded size of the message data
  776. func (r *reply) size() uint32 {
  777. return uint32(len(r.data))
  778. }
  779. // replyBlockHeaders creates a reply with a batch of block headers
  780. func (p *clientPeer) replyBlockHeaders(reqID uint64, headers []*types.Header) *reply {
  781. data, _ := rlp.EncodeToBytes(headers)
  782. return &reply{p.rw, BlockHeadersMsg, reqID, data}
  783. }
  784. // replyBlockBodiesRLP creates a reply with a batch of block contents from
  785. // an already RLP encoded format.
  786. func (p *clientPeer) replyBlockBodiesRLP(reqID uint64, bodies []rlp.RawValue) *reply {
  787. data, _ := rlp.EncodeToBytes(bodies)
  788. return &reply{p.rw, BlockBodiesMsg, reqID, data}
  789. }
  790. // replyCode creates a reply with a batch of arbitrary internal data, corresponding to the
  791. // hashes requested.
  792. func (p *clientPeer) replyCode(reqID uint64, codes [][]byte) *reply {
  793. data, _ := rlp.EncodeToBytes(codes)
  794. return &reply{p.rw, CodeMsg, reqID, data}
  795. }
  796. // replyReceiptsRLP creates a reply with a batch of transaction receipts, corresponding to the
  797. // ones requested from an already RLP encoded format.
  798. func (p *clientPeer) replyReceiptsRLP(reqID uint64, receipts []rlp.RawValue) *reply {
  799. data, _ := rlp.EncodeToBytes(receipts)
  800. return &reply{p.rw, ReceiptsMsg, reqID, data}
  801. }
  802. // replyProofsV2 creates a reply with a batch of merkle proofs, corresponding to the ones requested.
  803. func (p *clientPeer) replyProofsV2(reqID uint64, proofs light.NodeList) *reply {
  804. data, _ := rlp.EncodeToBytes(proofs)
  805. return &reply{p.rw, ProofsV2Msg, reqID, data}
  806. }
  807. // replyHelperTrieProofs creates a reply with a batch of HelperTrie proofs, corresponding to the ones requested.
  808. func (p *clientPeer) replyHelperTrieProofs(reqID uint64, resp HelperTrieResps) *reply {
  809. data, _ := rlp.EncodeToBytes(resp)
  810. return &reply{p.rw, HelperTrieProofsMsg, reqID, data}
  811. }
  812. // replyTxStatus creates a reply with a batch of transaction status records, corresponding to the ones requested.
  813. func (p *clientPeer) replyTxStatus(reqID uint64, stats []light.TxStatus) *reply {
  814. data, _ := rlp.EncodeToBytes(stats)
  815. return &reply{p.rw, TxStatusMsg, reqID, data}
  816. }
  817. // sendAnnounce announces the availability of a number of blocks through
  818. // a hash notification.
  819. func (p *clientPeer) sendAnnounce(request announceData) error {
  820. return p2p.Send(p.rw, AnnounceMsg, request)
  821. }
  822. // allowInactive implements clientPoolPeer
  823. func (p *clientPeer) allowInactive() bool {
  824. return false
  825. }
  826. // updateCapacity updates the request serving capacity assigned to a given client
  827. // and also sends an announcement about the updated flow control parameters
  828. func (p *clientPeer) updateCapacity(cap uint64) {
  829. p.lock.Lock()
  830. defer p.lock.Unlock()
  831. if cap != p.fcParams.MinRecharge {
  832. p.fcParams = flowcontrol.ServerParams{MinRecharge: cap, BufLimit: cap * bufLimitRatio}
  833. p.fcClient.UpdateParams(p.fcParams)
  834. var kvList keyValueList
  835. kvList = kvList.add("flowControl/MRR", cap)
  836. kvList = kvList.add("flowControl/BL", cap*bufLimitRatio)
  837. p.queueSend(func() { p.sendAnnounce(announceData{Update: kvList}) })
  838. }
  839. }
  840. // freezeClient temporarily puts the client in a frozen state which means all
  841. // unprocessed and subsequent requests are dropped. Unfreezing happens automatically
  842. // after a short time if the client's buffer value is at least in the slightly positive
  843. // region. The client is also notified about being frozen/unfrozen with a Stop/Resume
  844. // message.
  845. func (p *clientPeer) freezeClient() {
  846. if p.version < lpv3 {
  847. // if Stop/Resume is not supported then just drop the peer after setting
  848. // its frozen status permanently
  849. atomic.StoreUint32(&p.frozen, 1)
  850. p.Peer.Disconnect(p2p.DiscUselessPeer)
  851. return
  852. }
  853. if atomic.SwapUint32(&p.frozen, 1) == 0 {
  854. go func() {
  855. p.sendStop()
  856. time.Sleep(freezeTimeBase + time.Duration(rand.Int63n(int64(freezeTimeRandom))))
  857. for {
  858. bufValue, bufLimit := p.fcClient.BufferStatus()
  859. if bufLimit == 0 {
  860. return
  861. }
  862. if bufValue <= bufLimit/8 {
  863. time.Sleep(freezeCheckPeriod)
  864. } else {
  865. atomic.StoreUint32(&p.frozen, 0)
  866. p.sendResume(bufValue)
  867. break
  868. }
  869. }
  870. }()
  871. }
  872. }
  873. // Handshake executes the les protocol handshake, negotiating version number,
  874. // network IDs, difficulties, head and genesis blocks.
  875. func (p *clientPeer) Handshake(td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, forkID forkid.ID, forkFilter forkid.Filter, server *LesServer) error {
  876. recentTx := server.handler.blockchain.TxLookupLimit()
  877. if recentTx != txIndexUnlimited {
  878. if recentTx < blockSafetyMargin {
  879. recentTx = txIndexDisabled
  880. } else {
  881. recentTx -= blockSafetyMargin - txIndexRecentOffset
  882. }
  883. }
  884. if server.config.UltraLightOnlyAnnounce {
  885. recentTx = txIndexDisabled
  886. }
  887. if recentTx != txIndexUnlimited && p.version < lpv4 {
  888. return errors.New("Cannot serve old clients without a complete tx index")
  889. }
  890. // Note: clientPeer.headInfo should contain the last head announced to the client by us.
  891. // The values announced in the handshake are dummy values for compatibility reasons and should be ignored.
  892. p.headInfo = blockInfo{Hash: head, Number: headNum, Td: td}
  893. return p.handshake(td, head, headNum, genesis, forkID, forkFilter, func(lists *keyValueList) {
  894. // Add some information which services server can offer.
  895. if !server.config.UltraLightOnlyAnnounce {
  896. *lists = (*lists).add("serveHeaders", nil)
  897. *lists = (*lists).add("serveChainSince", uint64(0))
  898. *lists = (*lists).add("serveStateSince", uint64(0))
  899. // If local ethereum node is running in archive mode, advertise ourselves we have
  900. // all version state data. Otherwise only recent state is available.
  901. stateRecent := uint64(core.TriesInMemory - blockSafetyMargin)
  902. if server.archiveMode {
  903. stateRecent = 0
  904. }
  905. *lists = (*lists).add("serveRecentState", stateRecent)
  906. *lists = (*lists).add("txRelay", nil)
  907. }
  908. if p.version >= lpv4 {
  909. *lists = (*lists).add("recentTxLookup", recentTx)
  910. }
  911. *lists = (*lists).add("flowControl/BL", server.defParams.BufLimit)
  912. *lists = (*lists).add("flowControl/MRR", server.defParams.MinRecharge)
  913. var costList RequestCostList
  914. if server.costTracker.testCostList != nil {
  915. costList = server.costTracker.testCostList
  916. } else {
  917. costList = server.costTracker.makeCostList(server.costTracker.globalFactor())
  918. }
  919. *lists = (*lists).add("flowControl/MRC", costList)
  920. p.fcCosts = costList.decode(ProtocolLengths[uint(p.version)])
  921. p.fcParams = server.defParams
  922. // Add advertised checkpoint and register block height which
  923. // client can verify the checkpoint validity.
  924. if server.oracle != nil && server.oracle.IsRunning() {
  925. cp, height := server.oracle.StableCheckpoint()
  926. if cp != nil {
  927. *lists = (*lists).add("checkpoint/value", cp)
  928. *lists = (*lists).add("checkpoint/registerHeight", height)
  929. }
  930. }
  931. }, func(recv keyValueMap) error {
  932. p.server = recv.get("flowControl/MRR", nil) == nil
  933. if p.server {
  934. p.announceType = announceTypeNone // connected to another server, send no messages
  935. } else {
  936. if recv.get("announceType", &p.announceType) != nil {
  937. // set default announceType on server side
  938. p.announceType = announceTypeSimple
  939. }
  940. p.fcClient = flowcontrol.NewClientNode(server.fcManager, p.fcParams)
  941. }
  942. return nil
  943. })
  944. }
  945. func (p *clientPeer) bumpInvalid() {
  946. p.invalidLock.Lock()
  947. p.invalidCount.Add(1, mclock.Now())
  948. p.invalidLock.Unlock()
  949. }
  950. func (p *clientPeer) getInvalid() uint64 {
  951. p.invalidLock.RLock()
  952. defer p.invalidLock.RUnlock()
  953. return p.invalidCount.Value(mclock.Now())
  954. }
  955. // serverPeerSubscriber is an interface to notify services about added or
  956. // removed server peers
  957. type serverPeerSubscriber interface {
  958. registerPeer(*serverPeer)
  959. unregisterPeer(*serverPeer)
  960. }
  961. // serverPeerSet represents the set of active server peers currently
  962. // participating in the Light Ethereum sub-protocol.
  963. type serverPeerSet struct {
  964. peers map[string]*serverPeer
  965. // subscribers is a batch of subscribers and peerset will notify
  966. // these subscribers when the peerset changes(new server peer is
  967. // added or removed)
  968. subscribers []serverPeerSubscriber
  969. closed bool
  970. lock sync.RWMutex
  971. }
  972. // newServerPeerSet creates a new peer set to track the active server peers.
  973. func newServerPeerSet() *serverPeerSet {
  974. return &serverPeerSet{peers: make(map[string]*serverPeer)}
  975. }
  976. // subscribe adds a service to be notified about added or removed
  977. // peers and also register all active peers into the given service.
  978. func (ps *serverPeerSet) subscribe(sub serverPeerSubscriber) {
  979. ps.lock.Lock()
  980. defer ps.lock.Unlock()
  981. ps.subscribers = append(ps.subscribers, sub)
  982. for _, p := range ps.peers {
  983. sub.registerPeer(p)
  984. }
  985. }
  986. // unSubscribe removes the specified service from the subscriber pool.
  987. func (ps *serverPeerSet) unSubscribe(sub serverPeerSubscriber) {
  988. ps.lock.Lock()
  989. defer ps.lock.Unlock()
  990. for i, s := range ps.subscribers {
  991. if s == sub {
  992. ps.subscribers = append(ps.subscribers[:i], ps.subscribers[i+1:]...)
  993. return
  994. }
  995. }
  996. }
  997. // register adds a new server peer into the set, or returns an error if the
  998. // peer is already known.
  999. func (ps *serverPeerSet) register(peer *serverPeer) error {
  1000. ps.lock.Lock()
  1001. defer ps.lock.Unlock()
  1002. if ps.closed {
  1003. return errClosed
  1004. }
  1005. if _, exist := ps.peers[peer.id]; exist {
  1006. return errAlreadyRegistered
  1007. }
  1008. ps.peers[peer.id] = peer
  1009. for _, sub := range ps.subscribers {
  1010. sub.registerPeer(peer)
  1011. }
  1012. return nil
  1013. }
  1014. // unregister removes a remote peer from the active set, disabling any further
  1015. // actions to/from that particular entity. It also initiates disconnection at
  1016. // the networking layer.
  1017. func (ps *serverPeerSet) unregister(id string) error {
  1018. ps.lock.Lock()
  1019. defer ps.lock.Unlock()
  1020. p, ok := ps.peers[id]
  1021. if !ok {
  1022. return errNotRegistered
  1023. }
  1024. delete(ps.peers, id)
  1025. for _, sub := range ps.subscribers {
  1026. sub.unregisterPeer(p)
  1027. }
  1028. p.Peer.Disconnect(p2p.DiscRequested)
  1029. return nil
  1030. }
  1031. // ids returns a list of all registered peer IDs
  1032. func (ps *serverPeerSet) ids() []string {
  1033. ps.lock.RLock()
  1034. defer ps.lock.RUnlock()
  1035. var ids []string
  1036. for id := range ps.peers {
  1037. ids = append(ids, id)
  1038. }
  1039. return ids
  1040. }
  1041. // peer retrieves the registered peer with the given id.
  1042. func (ps *serverPeerSet) peer(id string) *serverPeer {
  1043. ps.lock.RLock()
  1044. defer ps.lock.RUnlock()
  1045. return ps.peers[id]
  1046. }
  1047. // len returns if the current number of peers in the set.
  1048. func (ps *serverPeerSet) len() int {
  1049. ps.lock.RLock()
  1050. defer ps.lock.RUnlock()
  1051. return len(ps.peers)
  1052. }
  1053. // bestPeer retrieves the known peer with the currently highest total difficulty.
  1054. // If the peerset is "client peer set", then nothing meaningful will return. The
  1055. // reason is client peer never send back their latest status to server.
  1056. func (ps *serverPeerSet) bestPeer() *serverPeer {
  1057. ps.lock.RLock()
  1058. defer ps.lock.RUnlock()
  1059. var (
  1060. bestPeer *serverPeer
  1061. bestTd *big.Int
  1062. )
  1063. for _, p := range ps.peers {
  1064. if td := p.Td(); bestTd == nil || td.Cmp(bestTd) > 0 {
  1065. bestPeer, bestTd = p, td
  1066. }
  1067. }
  1068. return bestPeer
  1069. }
  1070. // allServerPeers returns all server peers in a list.
  1071. func (ps *serverPeerSet) allPeers() []*serverPeer {
  1072. ps.lock.RLock()
  1073. defer ps.lock.RUnlock()
  1074. list := make([]*serverPeer, 0, len(ps.peers))
  1075. for _, p := range ps.peers {
  1076. list = append(list, p)
  1077. }
  1078. return list
  1079. }
  1080. // close disconnects all peers. No new peers can be registered
  1081. // after close has returned.
  1082. func (ps *serverPeerSet) close() {
  1083. ps.lock.Lock()
  1084. defer ps.lock.Unlock()
  1085. for _, p := range ps.peers {
  1086. p.Disconnect(p2p.DiscQuitting)
  1087. }
  1088. ps.closed = true
  1089. }