server_handler.go 18 KB

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