server_handler.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. // Copyright 2019 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package les
  17. import (
  18. "errors"
  19. "sync"
  20. "sync/atomic"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/common/mclock"
  24. "github.com/ethereum/go-ethereum/core"
  25. "github.com/ethereum/go-ethereum/core/forkid"
  26. "github.com/ethereum/go-ethereum/core/rawdb"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/ethdb"
  29. "github.com/ethereum/go-ethereum/les/flowcontrol"
  30. "github.com/ethereum/go-ethereum/light"
  31. "github.com/ethereum/go-ethereum/log"
  32. "github.com/ethereum/go-ethereum/metrics"
  33. "github.com/ethereum/go-ethereum/p2p"
  34. "github.com/ethereum/go-ethereum/rlp"
  35. "github.com/ethereum/go-ethereum/trie"
  36. )
  37. const (
  38. softResponseLimit = 2 * 1024 * 1024 // Target maximum size of returned blocks, headers or node data.
  39. estHeaderRlpSize = 500 // Approximate size of an RLP encoded block header
  40. MaxHeaderFetch = 192 // Amount of block headers to be fetched per retrieval request
  41. MaxBodyFetch = 32 // Amount of block bodies to be fetched per retrieval request
  42. MaxReceiptFetch = 128 // Amount of transaction receipts to allow fetching per request
  43. MaxCodeFetch = 64 // Amount of contract codes to allow fetching per request
  44. MaxProofsFetch = 64 // Amount of merkle proofs to be fetched per retrieval request
  45. MaxHelperTrieProofsFetch = 64 // Amount of helper tries to be fetched per retrieval request
  46. MaxTxSend = 64 // Amount of transactions to be send per request
  47. MaxTxStatus = 256 // Amount of transactions to queried per request
  48. )
  49. var (
  50. errTooManyInvalidRequest = errors.New("too many invalid requests made")
  51. )
  52. // serverHandler is responsible for serving light client and process
  53. // all incoming light requests.
  54. type serverHandler struct {
  55. forkFilter forkid.Filter
  56. blockchain *core.BlockChain
  57. chainDb ethdb.Database
  58. txpool *core.TxPool
  59. server *LesServer
  60. closeCh chan struct{} // Channel used to exit all background routines of handler.
  61. wg sync.WaitGroup // WaitGroup used to track all background routines of handler.
  62. synced func() bool // Callback function used to determine whether local node is synced.
  63. // Testing fields
  64. addTxsSync bool
  65. }
  66. func newServerHandler(server *LesServer, blockchain *core.BlockChain, chainDb ethdb.Database, txpool *core.TxPool, synced func() bool) *serverHandler {
  67. handler := &serverHandler{
  68. forkFilter: forkid.NewFilter(blockchain),
  69. server: server,
  70. blockchain: blockchain,
  71. chainDb: chainDb,
  72. txpool: txpool,
  73. closeCh: make(chan struct{}),
  74. synced: synced,
  75. }
  76. return handler
  77. }
  78. // start starts the server handler.
  79. func (h *serverHandler) start() {
  80. h.wg.Add(1)
  81. go h.broadcastLoop()
  82. }
  83. // stop stops the server handler.
  84. func (h *serverHandler) stop() {
  85. close(h.closeCh)
  86. h.wg.Wait()
  87. }
  88. // runPeer is the p2p protocol run function for the given version.
  89. func (h *serverHandler) runPeer(version uint, p *p2p.Peer, rw p2p.MsgReadWriter) error {
  90. peer := newClientPeer(int(version), h.server.config.NetworkId, p, newMeteredMsgWriter(rw, int(version)))
  91. defer peer.close()
  92. h.wg.Add(1)
  93. defer h.wg.Done()
  94. return h.handle(peer)
  95. }
  96. func (h *serverHandler) handle(p *clientPeer) error {
  97. p.Log().Debug("Light Ethereum peer connected", "name", p.Name())
  98. // Execute the LES handshake
  99. var (
  100. head = h.blockchain.CurrentHeader()
  101. hash = head.Hash()
  102. number = head.Number.Uint64()
  103. td = h.blockchain.GetTd(hash, number)
  104. forkID = forkid.NewID(h.blockchain.Config(), h.blockchain.Genesis().Hash(), h.blockchain.CurrentBlock().NumberU64())
  105. )
  106. if err := p.Handshake(td, hash, number, h.blockchain.Genesis().Hash(), forkID, h.forkFilter, h.server); err != nil {
  107. p.Log().Debug("Light Ethereum handshake failed", "err", err)
  108. return err
  109. }
  110. // Connected to another server, no messages expected, just wait for disconnection
  111. if p.server {
  112. if err := h.server.serverset.register(p); err != nil {
  113. return err
  114. }
  115. _, err := p.rw.ReadMsg()
  116. h.server.serverset.unregister(p)
  117. return err
  118. }
  119. // Setup flow control mechanism for the peer
  120. p.fcClient = flowcontrol.NewClientNode(h.server.fcManager, p.fcParams)
  121. defer p.fcClient.Disconnect()
  122. // Reject light clients if server is not synced. Put this checking here, so
  123. // that "non-synced" les-server peers are still allowed to keep the connection.
  124. if !h.synced() {
  125. p.Log().Debug("Light server not synced, rejecting peer")
  126. return p2p.DiscRequested
  127. }
  128. // Register the peer into the peerset and clientpool
  129. if err := h.server.peers.register(p); err != nil {
  130. return err
  131. }
  132. if p.balance = h.server.clientPool.Register(p); p.balance == nil {
  133. h.server.peers.unregister(p.ID())
  134. p.Log().Debug("Client pool already closed")
  135. return p2p.DiscRequested
  136. }
  137. p.connectedAt = mclock.Now()
  138. var wg sync.WaitGroup // Wait group used to track all in-flight task routines.
  139. defer func() {
  140. wg.Wait() // Ensure all background task routines have exited.
  141. h.server.clientPool.Unregister(p)
  142. h.server.peers.unregister(p.ID())
  143. p.balance = nil
  144. connectionTimer.Update(time.Duration(mclock.Now() - p.connectedAt))
  145. }()
  146. // Mark the peer as being served.
  147. atomic.StoreUint32(&p.serving, 1)
  148. defer atomic.StoreUint32(&p.serving, 0)
  149. // Spawn a main loop to handle all incoming messages.
  150. for {
  151. select {
  152. case err := <-p.errCh:
  153. p.Log().Debug("Failed to send light ethereum response", "err", err)
  154. return err
  155. default:
  156. }
  157. if err := h.handleMsg(p, &wg); err != nil {
  158. p.Log().Debug("Light Ethereum message handling failed", "err", err)
  159. return err
  160. }
  161. }
  162. }
  163. // beforeHandle will do a series of prechecks before handling message.
  164. func (h *serverHandler) beforeHandle(p *clientPeer, reqID, responseCount uint64, msg p2p.Msg, reqCnt uint64, maxCount uint64) (*servingTask, uint64) {
  165. // Ensure that the request sent by client peer is valid
  166. inSizeCost := h.server.costTracker.realCost(0, msg.Size, 0)
  167. if reqCnt == 0 || reqCnt > maxCount {
  168. p.fcClient.OneTimeCost(inSizeCost)
  169. return nil, 0
  170. }
  171. // Ensure that the client peer complies with the flow control
  172. // rules agreed by both sides.
  173. if p.isFrozen() {
  174. p.fcClient.OneTimeCost(inSizeCost)
  175. return nil, 0
  176. }
  177. maxCost := p.fcCosts.getMaxCost(msg.Code, reqCnt)
  178. accepted, bufShort, priority := p.fcClient.AcceptRequest(reqID, responseCount, maxCost)
  179. if !accepted {
  180. p.freeze()
  181. p.Log().Error("Request came too early", "remaining", common.PrettyDuration(time.Duration(bufShort*1000000/p.fcParams.MinRecharge)))
  182. p.fcClient.OneTimeCost(inSizeCost)
  183. return nil, 0
  184. }
  185. // Create a multi-stage task, estimate the time it takes for the task to
  186. // execute, and cache it in the request service queue.
  187. factor := h.server.costTracker.globalFactor()
  188. if factor < 0.001 {
  189. factor = 1
  190. p.Log().Error("Invalid global cost factor", "factor", factor)
  191. }
  192. maxTime := uint64(float64(maxCost) / factor)
  193. task := h.server.servingQueue.newTask(p, maxTime, priority)
  194. if !task.start() {
  195. p.fcClient.RequestProcessed(reqID, responseCount, maxCost, inSizeCost)
  196. return nil, 0
  197. }
  198. return task, maxCost
  199. }
  200. // Afterhandle will perform a series of operations after message handling,
  201. // such as updating flow control data, sending reply, etc.
  202. func (h *serverHandler) afterHandle(p *clientPeer, reqID, responseCount uint64, msg p2p.Msg, maxCost uint64, reqCnt uint64, task *servingTask, reply *reply) {
  203. if reply != nil {
  204. task.done()
  205. }
  206. p.responseLock.Lock()
  207. defer p.responseLock.Unlock()
  208. // Short circuit if the client is already frozen.
  209. if p.isFrozen() {
  210. realCost := h.server.costTracker.realCost(task.servingTime, msg.Size, 0)
  211. p.fcClient.RequestProcessed(reqID, responseCount, maxCost, realCost)
  212. return
  213. }
  214. // Positive correction buffer value with real cost.
  215. var replySize uint32
  216. if reply != nil {
  217. replySize = reply.size()
  218. }
  219. var realCost uint64
  220. if h.server.costTracker.testing {
  221. realCost = maxCost // Assign a fake cost for testing purpose
  222. } else {
  223. realCost = h.server.costTracker.realCost(task.servingTime, msg.Size, replySize)
  224. if realCost > maxCost {
  225. realCost = maxCost
  226. }
  227. }
  228. bv := p.fcClient.RequestProcessed(reqID, responseCount, maxCost, realCost)
  229. if reply != nil {
  230. // Feed cost tracker request serving statistic.
  231. h.server.costTracker.updateStats(msg.Code, reqCnt, task.servingTime, realCost)
  232. // Reduce priority "balance" for the specific peer.
  233. p.balance.RequestServed(realCost)
  234. p.queueSend(func() {
  235. if err := reply.send(bv); err != nil {
  236. select {
  237. case p.errCh <- err:
  238. default:
  239. }
  240. }
  241. })
  242. }
  243. }
  244. // handleMsg is invoked whenever an inbound message is received from a remote
  245. // peer. The remote connection is torn down upon returning any error.
  246. func (h *serverHandler) handleMsg(p *clientPeer, wg *sync.WaitGroup) error {
  247. // Read the next message from the remote peer, and ensure it's fully consumed
  248. msg, err := p.rw.ReadMsg()
  249. if err != nil {
  250. return err
  251. }
  252. p.Log().Trace("Light Ethereum message arrived", "code", msg.Code, "bytes", msg.Size)
  253. // Discard large message which exceeds the limitation.
  254. if msg.Size > ProtocolMaxMsgSize {
  255. clientErrorMeter.Mark(1)
  256. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  257. }
  258. defer msg.Discard()
  259. // Lookup the request handler table, ensure it's supported
  260. // message type by the protocol.
  261. req, ok := Les3[msg.Code]
  262. if !ok {
  263. p.Log().Trace("Received invalid message", "code", msg.Code)
  264. clientErrorMeter.Mark(1)
  265. return errResp(ErrInvalidMsgCode, "%v", msg.Code)
  266. }
  267. p.Log().Trace("Received " + req.Name)
  268. // Decode the p2p message, resolve the concrete handler for it.
  269. serve, reqID, reqCnt, err := req.Handle(msg)
  270. if err != nil {
  271. clientErrorMeter.Mark(1)
  272. return errResp(ErrDecode, "%v: %v", msg, err)
  273. }
  274. if metrics.EnabledExpensive {
  275. req.InPacketsMeter.Mark(1)
  276. req.InTrafficMeter.Mark(int64(msg.Size))
  277. }
  278. p.responseCount++
  279. responseCount := p.responseCount
  280. // First check this client message complies all rules before
  281. // handling it and return a processor if all checks are passed.
  282. task, maxCost := h.beforeHandle(p, reqID, responseCount, msg, reqCnt, req.MaxCount)
  283. if task == nil {
  284. return nil
  285. }
  286. wg.Add(1)
  287. go func() {
  288. defer wg.Done()
  289. reply := serve(h, p, task.waitOrStop)
  290. h.afterHandle(p, reqID, responseCount, msg, maxCost, reqCnt, task, reply)
  291. if metrics.EnabledExpensive {
  292. size := uint32(0)
  293. if reply != nil {
  294. size = reply.size()
  295. }
  296. req.OutPacketsMeter.Mark(1)
  297. req.OutTrafficMeter.Mark(int64(size))
  298. req.ServingTimeMeter.Update(time.Duration(task.servingTime))
  299. }
  300. }()
  301. // If the client has made too much invalid request(e.g. request a non-existent data),
  302. // reject them to prevent SPAM attack.
  303. if p.getInvalid() > maxRequestErrors {
  304. clientErrorMeter.Mark(1)
  305. return errTooManyInvalidRequest
  306. }
  307. return nil
  308. }
  309. // BlockChain implements serverBackend
  310. func (h *serverHandler) BlockChain() *core.BlockChain {
  311. return h.blockchain
  312. }
  313. // TxPool implements serverBackend
  314. func (h *serverHandler) TxPool() *core.TxPool {
  315. return h.txpool
  316. }
  317. // ArchiveMode implements serverBackend
  318. func (h *serverHandler) ArchiveMode() bool {
  319. return h.server.archiveMode
  320. }
  321. // AddTxsSync implements serverBackend
  322. func (h *serverHandler) AddTxsSync() bool {
  323. return h.addTxsSync
  324. }
  325. // getAccount retrieves an account from the state based on root.
  326. func getAccount(triedb *trie.Database, root, hash common.Hash) (types.StateAccount, error) {
  327. trie, err := trie.New(common.Hash{}, root, triedb)
  328. if err != nil {
  329. return types.StateAccount{}, err
  330. }
  331. blob, err := trie.TryGet(hash[:])
  332. if err != nil {
  333. return types.StateAccount{}, err
  334. }
  335. var acc types.StateAccount
  336. if err = rlp.DecodeBytes(blob, &acc); err != nil {
  337. return types.StateAccount{}, err
  338. }
  339. return acc, nil
  340. }
  341. // GetHelperTrie returns the post-processed trie root for the given trie ID and section index
  342. func (h *serverHandler) GetHelperTrie(typ uint, index uint64) *trie.Trie {
  343. var (
  344. root common.Hash
  345. prefix string
  346. )
  347. switch typ {
  348. case htCanonical:
  349. sectionHead := rawdb.ReadCanonicalHash(h.chainDb, (index+1)*h.server.iConfig.ChtSize-1)
  350. root, prefix = light.GetChtRoot(h.chainDb, index, sectionHead), light.ChtTablePrefix
  351. case htBloomBits:
  352. sectionHead := rawdb.ReadCanonicalHash(h.chainDb, (index+1)*h.server.iConfig.BloomTrieSize-1)
  353. root, prefix = light.GetBloomTrieRoot(h.chainDb, index, sectionHead), light.BloomTrieTablePrefix
  354. }
  355. if root == (common.Hash{}) {
  356. return nil
  357. }
  358. trie, _ := trie.New(common.Hash{}, root, trie.NewDatabase(rawdb.NewTable(h.chainDb, prefix)))
  359. return trie
  360. }
  361. // broadcastLoop broadcasts new block information to all connected light
  362. // clients. According to the agreement between client and server, server should
  363. // only broadcast new announcement if the total difficulty is higher than the
  364. // last one. Besides server will add the signature if client requires.
  365. func (h *serverHandler) broadcastLoop() {
  366. defer h.wg.Done()
  367. headCh := make(chan core.ChainHeadEvent, 10)
  368. headSub := h.blockchain.SubscribeChainHeadEvent(headCh)
  369. defer headSub.Unsubscribe()
  370. var (
  371. lastHead = h.blockchain.CurrentHeader()
  372. lastTd = common.Big0
  373. )
  374. for {
  375. select {
  376. case ev := <-headCh:
  377. header := ev.Block.Header()
  378. hash, number := header.Hash(), header.Number.Uint64()
  379. td := h.blockchain.GetTd(hash, number)
  380. if td == nil || td.Cmp(lastTd) <= 0 {
  381. continue
  382. }
  383. var reorg uint64
  384. if lastHead != nil {
  385. // If a setHead has been performed, the common ancestor can be nil.
  386. if ancestor := rawdb.FindCommonAncestor(h.chainDb, header, lastHead); ancestor != nil {
  387. reorg = lastHead.Number.Uint64() - ancestor.Number.Uint64()
  388. }
  389. }
  390. lastHead, lastTd = header, td
  391. log.Debug("Announcing block to peers", "number", number, "hash", hash, "td", td, "reorg", reorg)
  392. h.server.peers.broadcast(announceData{Hash: hash, Number: number, Td: td, ReorgDepth: reorg})
  393. case <-h.closeCh:
  394. return
  395. }
  396. }
  397. }