peer.go 45 KB

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