peer.go 39 KB

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