peer.go 41 KB

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