peer.go 43 KB

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