server_handler.go 14 KB

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