peer.go 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  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. // freezeClient temporarily puts the client in a frozen state which means all
  887. // unprocessed and subsequent requests are dropped. Unfreezing happens automatically
  888. // after a short time if the client's buffer value is at least in the slightly positive
  889. // region. The client is also notified about being frozen/unfrozen with a Stop/Resume
  890. // message.
  891. func (p *clientPeer) freezeClient() {
  892. if p.version < lpv3 {
  893. // if Stop/Resume is not supported then just drop the peer after setting
  894. // its frozen status permanently
  895. atomic.StoreUint32(&p.frozen, 1)
  896. p.Peer.Disconnect(p2p.DiscUselessPeer)
  897. return
  898. }
  899. if atomic.SwapUint32(&p.frozen, 1) == 0 {
  900. go func() {
  901. p.sendStop()
  902. time.Sleep(freezeTimeBase + time.Duration(rand.Int63n(int64(freezeTimeRandom))))
  903. for {
  904. bufValue, bufLimit := p.fcClient.BufferStatus()
  905. if bufLimit == 0 {
  906. return
  907. }
  908. if bufValue <= bufLimit/8 {
  909. time.Sleep(freezeCheckPeriod)
  910. } else {
  911. atomic.StoreUint32(&p.frozen, 0)
  912. p.sendResume(bufValue)
  913. break
  914. }
  915. }
  916. }()
  917. }
  918. }
  919. // Handshake executes the les protocol handshake, negotiating version number,
  920. // network IDs, difficulties, head and genesis blocks.
  921. func (p *clientPeer) Handshake(td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, forkID forkid.ID, forkFilter forkid.Filter, server *LesServer) error {
  922. recentTx := server.handler.blockchain.TxLookupLimit()
  923. if recentTx != txIndexUnlimited {
  924. if recentTx < blockSafetyMargin {
  925. recentTx = txIndexDisabled
  926. } else {
  927. recentTx -= blockSafetyMargin - txIndexRecentOffset
  928. }
  929. }
  930. if server.config.UltraLightOnlyAnnounce {
  931. recentTx = txIndexDisabled
  932. }
  933. if recentTx != txIndexUnlimited && p.version < lpv4 {
  934. return errors.New("Cannot serve old clients without a complete tx index")
  935. }
  936. // Note: clientPeer.headInfo should contain the last head announced to the client by us.
  937. // The values announced in the handshake are dummy values for compatibility reasons and should be ignored.
  938. p.headInfo = blockInfo{Hash: head, Number: headNum, Td: td}
  939. return p.handshake(td, head, headNum, genesis, forkID, forkFilter, func(lists *keyValueList) {
  940. // Add some information which services server can offer.
  941. if !server.config.UltraLightOnlyAnnounce {
  942. *lists = (*lists).add("serveHeaders", nil)
  943. *lists = (*lists).add("serveChainSince", uint64(0))
  944. *lists = (*lists).add("serveStateSince", uint64(0))
  945. // If local ethereum node is running in archive mode, advertise ourselves we have
  946. // all version state data. Otherwise only recent state is available.
  947. stateRecent := uint64(core.TriesInMemory - blockSafetyMargin)
  948. if server.archiveMode {
  949. stateRecent = 0
  950. }
  951. *lists = (*lists).add("serveRecentState", stateRecent)
  952. *lists = (*lists).add("txRelay", nil)
  953. }
  954. if p.version >= lpv4 {
  955. *lists = (*lists).add("recentTxLookup", recentTx)
  956. }
  957. *lists = (*lists).add("flowControl/BL", server.defParams.BufLimit)
  958. *lists = (*lists).add("flowControl/MRR", server.defParams.MinRecharge)
  959. var costList RequestCostList
  960. if server.costTracker.testCostList != nil {
  961. costList = server.costTracker.testCostList
  962. } else {
  963. costList = server.costTracker.makeCostList(server.costTracker.globalFactor())
  964. }
  965. *lists = (*lists).add("flowControl/MRC", costList)
  966. p.fcCosts = costList.decode(ProtocolLengths[uint(p.version)])
  967. p.fcParams = server.defParams
  968. // Add advertised checkpoint and register block height which
  969. // client can verify the checkpoint validity.
  970. if server.oracle != nil && server.oracle.IsRunning() {
  971. cp, height := server.oracle.StableCheckpoint()
  972. if cp != nil {
  973. *lists = (*lists).add("checkpoint/value", cp)
  974. *lists = (*lists).add("checkpoint/registerHeight", height)
  975. }
  976. }
  977. }, func(recv keyValueMap) error {
  978. p.server = recv.get("flowControl/MRR", nil) == nil
  979. if p.server {
  980. p.announceType = announceTypeNone // connected to another server, send no messages
  981. } else {
  982. if recv.get("announceType", &p.announceType) != nil {
  983. // set default announceType on server side
  984. p.announceType = announceTypeSimple
  985. }
  986. }
  987. return nil
  988. })
  989. }
  990. func (p *clientPeer) bumpInvalid() {
  991. p.invalidLock.Lock()
  992. p.invalidCount.Add(1, mclock.Now())
  993. p.invalidLock.Unlock()
  994. }
  995. func (p *clientPeer) getInvalid() uint64 {
  996. p.invalidLock.RLock()
  997. defer p.invalidLock.RUnlock()
  998. return p.invalidCount.Value(mclock.Now())
  999. }
  1000. // Disconnect implements vfs.clientPeer
  1001. func (p *clientPeer) Disconnect() {
  1002. p.Peer.Disconnect(p2p.DiscRequested)
  1003. }
  1004. // serverPeerSubscriber is an interface to notify services about added or
  1005. // removed server peers
  1006. type serverPeerSubscriber interface {
  1007. registerPeer(*serverPeer)
  1008. unregisterPeer(*serverPeer)
  1009. }
  1010. // serverPeerSet represents the set of active server peers currently
  1011. // participating in the Light Ethereum sub-protocol.
  1012. type serverPeerSet struct {
  1013. peers map[string]*serverPeer
  1014. // subscribers is a batch of subscribers and peerset will notify
  1015. // these subscribers when the peerset changes(new server peer is
  1016. // added or removed)
  1017. subscribers []serverPeerSubscriber
  1018. closed bool
  1019. lock sync.RWMutex
  1020. }
  1021. // newServerPeerSet creates a new peer set to track the active server peers.
  1022. func newServerPeerSet() *serverPeerSet {
  1023. return &serverPeerSet{peers: make(map[string]*serverPeer)}
  1024. }
  1025. // subscribe adds a service to be notified about added or removed
  1026. // peers and also register all active peers into the given service.
  1027. func (ps *serverPeerSet) subscribe(sub serverPeerSubscriber) {
  1028. ps.lock.Lock()
  1029. defer ps.lock.Unlock()
  1030. ps.subscribers = append(ps.subscribers, sub)
  1031. for _, p := range ps.peers {
  1032. sub.registerPeer(p)
  1033. }
  1034. }
  1035. // unSubscribe removes the specified service from the subscriber pool.
  1036. func (ps *serverPeerSet) unSubscribe(sub serverPeerSubscriber) {
  1037. ps.lock.Lock()
  1038. defer ps.lock.Unlock()
  1039. for i, s := range ps.subscribers {
  1040. if s == sub {
  1041. ps.subscribers = append(ps.subscribers[:i], ps.subscribers[i+1:]...)
  1042. return
  1043. }
  1044. }
  1045. }
  1046. // register adds a new server peer into the set, or returns an error if the
  1047. // peer is already known.
  1048. func (ps *serverPeerSet) register(peer *serverPeer) error {
  1049. ps.lock.Lock()
  1050. defer ps.lock.Unlock()
  1051. if ps.closed {
  1052. return errClosed
  1053. }
  1054. if _, exist := ps.peers[peer.id]; exist {
  1055. return errAlreadyRegistered
  1056. }
  1057. ps.peers[peer.id] = peer
  1058. for _, sub := range ps.subscribers {
  1059. sub.registerPeer(peer)
  1060. }
  1061. return nil
  1062. }
  1063. // unregister removes a remote peer from the active set, disabling any further
  1064. // actions to/from that particular entity. It also initiates disconnection at
  1065. // the networking layer.
  1066. func (ps *serverPeerSet) unregister(id string) error {
  1067. ps.lock.Lock()
  1068. defer ps.lock.Unlock()
  1069. p, ok := ps.peers[id]
  1070. if !ok {
  1071. return errNotRegistered
  1072. }
  1073. delete(ps.peers, id)
  1074. for _, sub := range ps.subscribers {
  1075. sub.unregisterPeer(p)
  1076. }
  1077. p.Peer.Disconnect(p2p.DiscRequested)
  1078. return nil
  1079. }
  1080. // ids returns a list of all registered peer IDs
  1081. func (ps *serverPeerSet) ids() []string {
  1082. ps.lock.RLock()
  1083. defer ps.lock.RUnlock()
  1084. var ids []string
  1085. for id := range ps.peers {
  1086. ids = append(ids, id)
  1087. }
  1088. return ids
  1089. }
  1090. // peer retrieves the registered peer with the given id.
  1091. func (ps *serverPeerSet) peer(id string) *serverPeer {
  1092. ps.lock.RLock()
  1093. defer ps.lock.RUnlock()
  1094. return ps.peers[id]
  1095. }
  1096. // len returns if the current number of peers in the set.
  1097. func (ps *serverPeerSet) len() int {
  1098. ps.lock.RLock()
  1099. defer ps.lock.RUnlock()
  1100. return len(ps.peers)
  1101. }
  1102. // bestPeer retrieves the known peer with the currently highest total difficulty.
  1103. // If the peerset is "client peer set", then nothing meaningful will return. The
  1104. // reason is client peer never send back their latest status to server.
  1105. func (ps *serverPeerSet) bestPeer() *serverPeer {
  1106. ps.lock.RLock()
  1107. defer ps.lock.RUnlock()
  1108. var (
  1109. bestPeer *serverPeer
  1110. bestTd *big.Int
  1111. )
  1112. for _, p := range ps.peers {
  1113. if td := p.Td(); bestTd == nil || td.Cmp(bestTd) > 0 {
  1114. bestPeer, bestTd = p, td
  1115. }
  1116. }
  1117. return bestPeer
  1118. }
  1119. // allServerPeers returns all server peers in a list.
  1120. func (ps *serverPeerSet) allPeers() []*serverPeer {
  1121. ps.lock.RLock()
  1122. defer ps.lock.RUnlock()
  1123. list := make([]*serverPeer, 0, len(ps.peers))
  1124. for _, p := range ps.peers {
  1125. list = append(list, p)
  1126. }
  1127. return list
  1128. }
  1129. // close disconnects all peers. No new peers can be registered
  1130. // after close has returned.
  1131. func (ps *serverPeerSet) close() {
  1132. ps.lock.Lock()
  1133. defer ps.lock.Unlock()
  1134. for _, p := range ps.peers {
  1135. p.Disconnect(p2p.DiscQuitting)
  1136. }
  1137. ps.closed = true
  1138. }
  1139. // clientPeerSet represents the set of active client peers currently
  1140. // participating in the Light Ethereum sub-protocol.
  1141. type clientPeerSet struct {
  1142. peers map[enode.ID]*clientPeer
  1143. lock sync.RWMutex
  1144. closed bool
  1145. privateKey *ecdsa.PrivateKey
  1146. lastAnnounce, signedAnnounce announceData
  1147. }
  1148. // newClientPeerSet creates a new peer set to track the client peers.
  1149. func newClientPeerSet() *clientPeerSet {
  1150. return &clientPeerSet{peers: make(map[enode.ID]*clientPeer)}
  1151. }
  1152. // register adds a new peer into the peer set, or returns an error if the
  1153. // peer is already known.
  1154. func (ps *clientPeerSet) register(peer *clientPeer) error {
  1155. ps.lock.Lock()
  1156. defer ps.lock.Unlock()
  1157. if ps.closed {
  1158. return errClosed
  1159. }
  1160. if _, exist := ps.peers[peer.ID()]; exist {
  1161. return errAlreadyRegistered
  1162. }
  1163. ps.peers[peer.ID()] = peer
  1164. ps.announceOrStore(peer)
  1165. return nil
  1166. }
  1167. // unregister removes a remote peer from the peer set, disabling any further
  1168. // actions to/from that particular entity. It also initiates disconnection
  1169. // at the networking layer.
  1170. func (ps *clientPeerSet) unregister(id enode.ID) error {
  1171. ps.lock.Lock()
  1172. defer ps.lock.Unlock()
  1173. p, ok := ps.peers[id]
  1174. if !ok {
  1175. return errNotRegistered
  1176. }
  1177. delete(ps.peers, id)
  1178. p.Peer.Disconnect(p2p.DiscRequested)
  1179. return nil
  1180. }
  1181. // ids returns a list of all registered peer IDs
  1182. func (ps *clientPeerSet) ids() []enode.ID {
  1183. ps.lock.RLock()
  1184. defer ps.lock.RUnlock()
  1185. var ids []enode.ID
  1186. for id := range ps.peers {
  1187. ids = append(ids, id)
  1188. }
  1189. return ids
  1190. }
  1191. // peer retrieves the registered peer with the given id.
  1192. func (ps *clientPeerSet) peer(id enode.ID) *clientPeer {
  1193. ps.lock.RLock()
  1194. defer ps.lock.RUnlock()
  1195. return ps.peers[id]
  1196. }
  1197. // len returns if the current number of peers in the set.
  1198. func (ps *clientPeerSet) len() int {
  1199. ps.lock.RLock()
  1200. defer ps.lock.RUnlock()
  1201. return len(ps.peers)
  1202. }
  1203. // setSignerKey sets the signer key for signed announcements. Should be called before
  1204. // starting the protocol handler.
  1205. func (ps *clientPeerSet) setSignerKey(privateKey *ecdsa.PrivateKey) {
  1206. ps.privateKey = privateKey
  1207. }
  1208. // broadcast sends the given announcements to all active peers
  1209. func (ps *clientPeerSet) broadcast(announce announceData) {
  1210. ps.lock.Lock()
  1211. defer ps.lock.Unlock()
  1212. ps.lastAnnounce = announce
  1213. for _, peer := range ps.peers {
  1214. ps.announceOrStore(peer)
  1215. }
  1216. }
  1217. // announceOrStore sends the requested type of announcement to the given peer or stores
  1218. // it for later if the peer is inactive (capacity == 0).
  1219. func (ps *clientPeerSet) announceOrStore(p *clientPeer) {
  1220. if ps.lastAnnounce.Td == nil {
  1221. return
  1222. }
  1223. switch p.announceType {
  1224. case announceTypeSimple:
  1225. p.announceOrStore(ps.lastAnnounce)
  1226. case announceTypeSigned:
  1227. if ps.signedAnnounce.Hash != ps.lastAnnounce.Hash {
  1228. ps.signedAnnounce = ps.lastAnnounce
  1229. ps.signedAnnounce.sign(ps.privateKey)
  1230. }
  1231. p.announceOrStore(ps.signedAnnounce)
  1232. }
  1233. }
  1234. // close disconnects all peers. No new peers can be registered
  1235. // after close has returned.
  1236. func (ps *clientPeerSet) close() {
  1237. ps.lock.Lock()
  1238. defer ps.lock.Unlock()
  1239. for _, p := range ps.peers {
  1240. p.Peer.Disconnect(p2p.DiscQuitting)
  1241. }
  1242. ps.closed = true
  1243. }
  1244. // serverSet is a special set which contains all connected les servers.
  1245. // Les servers will also be discovered by discovery protocol because they
  1246. // also run the LES protocol. We can't drop them although they are useless
  1247. // for us(server) but for other protocols(e.g. ETH) upon the devp2p they
  1248. // may be useful.
  1249. type serverSet struct {
  1250. lock sync.Mutex
  1251. set map[string]*clientPeer
  1252. closed bool
  1253. }
  1254. func newServerSet() *serverSet {
  1255. return &serverSet{set: make(map[string]*clientPeer)}
  1256. }
  1257. func (s *serverSet) register(peer *clientPeer) error {
  1258. s.lock.Lock()
  1259. defer s.lock.Unlock()
  1260. if s.closed {
  1261. return errClosed
  1262. }
  1263. if _, exist := s.set[peer.id]; exist {
  1264. return errAlreadyRegistered
  1265. }
  1266. s.set[peer.id] = peer
  1267. return nil
  1268. }
  1269. func (s *serverSet) unregister(peer *clientPeer) error {
  1270. s.lock.Lock()
  1271. defer s.lock.Unlock()
  1272. if s.closed {
  1273. return errClosed
  1274. }
  1275. if _, exist := s.set[peer.id]; !exist {
  1276. return errNotRegistered
  1277. }
  1278. delete(s.set, peer.id)
  1279. peer.Peer.Disconnect(p2p.DiscQuitting)
  1280. return nil
  1281. }
  1282. func (s *serverSet) close() {
  1283. s.lock.Lock()
  1284. defer s.lock.Unlock()
  1285. for _, p := range s.set {
  1286. p.Peer.Disconnect(p2p.DiscQuitting)
  1287. }
  1288. s.closed = true
  1289. }