peer.go 39 KB

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