server_handler.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. // handleMsg is invoked whenever an inbound message is received from a remote
  188. // peer. The remote connection is torn down upon returning any error.
  189. func (h *serverHandler) handleMsg(p *clientPeer, wg *sync.WaitGroup) error {
  190. // Read the next message from the remote peer, and ensure it's fully consumed
  191. msg, err := p.rw.ReadMsg()
  192. if err != nil {
  193. return err
  194. }
  195. p.Log().Trace("Light Ethereum message arrived", "code", msg.Code, "bytes", msg.Size)
  196. // Discard large message which exceeds the limitation.
  197. if msg.Size > ProtocolMaxMsgSize {
  198. clientErrorMeter.Mark(1)
  199. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  200. }
  201. defer msg.Discard()
  202. p.responseCount++
  203. responseCount := p.responseCount
  204. req, ok := Les3[msg.Code]
  205. if !ok {
  206. p.Log().Trace("Received invalid message", "code", msg.Code)
  207. clientErrorMeter.Mark(1)
  208. return errResp(ErrInvalidMsgCode, "%v", msg.Code)
  209. }
  210. p.Log().Trace("Received " + req.Name)
  211. serve, reqID, reqCnt, err := req.Handle(msg)
  212. if err != nil {
  213. clientErrorMeter.Mark(1)
  214. return errResp(ErrDecode, "%v: %v", msg, err)
  215. }
  216. if metrics.EnabledExpensive {
  217. req.InPacketsMeter.Mark(1)
  218. req.InTrafficMeter.Mark(int64(msg.Size))
  219. }
  220. // Short circuit if the peer is already frozen or the request is invalid.
  221. inSizeCost := h.server.costTracker.realCost(0, msg.Size, 0)
  222. if p.isFrozen() || reqCnt == 0 || reqCnt > req.MaxCount {
  223. p.fcClient.OneTimeCost(inSizeCost)
  224. return nil
  225. }
  226. // Prepaid max cost units before request been serving.
  227. maxCost := p.fcCosts.getMaxCost(msg.Code, reqCnt)
  228. accepted, bufShort, priority := p.fcClient.AcceptRequest(reqID, responseCount, maxCost)
  229. if !accepted {
  230. p.freeze()
  231. p.Log().Error("Request came too early", "remaining", common.PrettyDuration(time.Duration(bufShort*1000000/p.fcParams.MinRecharge)))
  232. p.fcClient.OneTimeCost(inSizeCost)
  233. return nil
  234. }
  235. // Create a multi-stage task, estimate the time it takes for the task to
  236. // execute, and cache it in the request service queue.
  237. factor := h.server.costTracker.globalFactor()
  238. if factor < 0.001 {
  239. factor = 1
  240. p.Log().Error("Invalid global cost factor", "factor", factor)
  241. }
  242. maxTime := uint64(float64(maxCost) / factor)
  243. task := h.server.servingQueue.newTask(p, maxTime, priority)
  244. if task.start() {
  245. wg.Add(1)
  246. go func() {
  247. defer wg.Done()
  248. reply := serve(h, p, task.waitOrStop)
  249. if reply != nil {
  250. task.done()
  251. }
  252. p.responseLock.Lock()
  253. defer p.responseLock.Unlock()
  254. // Short circuit if the client is already frozen.
  255. if p.isFrozen() {
  256. realCost := h.server.costTracker.realCost(task.servingTime, msg.Size, 0)
  257. p.fcClient.RequestProcessed(reqID, responseCount, maxCost, realCost)
  258. return
  259. }
  260. // Positive correction buffer value with real cost.
  261. var replySize uint32
  262. if reply != nil {
  263. replySize = reply.size()
  264. }
  265. var realCost uint64
  266. if h.server.costTracker.testing {
  267. realCost = maxCost // Assign a fake cost for testing purpose
  268. } else {
  269. realCost = h.server.costTracker.realCost(task.servingTime, msg.Size, replySize)
  270. if realCost > maxCost {
  271. realCost = maxCost
  272. }
  273. }
  274. bv := p.fcClient.RequestProcessed(reqID, responseCount, maxCost, realCost)
  275. if reply != nil {
  276. // Feed cost tracker request serving statistic.
  277. h.server.costTracker.updateStats(msg.Code, reqCnt, task.servingTime, realCost)
  278. // Reduce priority "balance" for the specific peer.
  279. p.balance.RequestServed(realCost)
  280. p.queueSend(func() {
  281. if err := reply.send(bv); err != nil {
  282. select {
  283. case p.errCh <- err:
  284. default:
  285. }
  286. }
  287. })
  288. if metrics.EnabledExpensive {
  289. req.OutPacketsMeter.Mark(1)
  290. req.OutTrafficMeter.Mark(int64(replySize))
  291. req.ServingTimeMeter.Update(time.Duration(task.servingTime))
  292. }
  293. }
  294. }()
  295. } else {
  296. p.fcClient.RequestProcessed(reqID, responseCount, maxCost, inSizeCost)
  297. }
  298. // If the client has made too much invalid request(e.g. request a non-existent data),
  299. // reject them to prevent SPAM attack.
  300. if p.getInvalid() > maxRequestErrors {
  301. clientErrorMeter.Mark(1)
  302. return errTooManyInvalidRequest
  303. }
  304. return nil
  305. }
  306. // BlockChain implements serverBackend
  307. func (h *serverHandler) BlockChain() *core.BlockChain {
  308. return h.blockchain
  309. }
  310. // TxPool implements serverBackend
  311. func (h *serverHandler) TxPool() *core.TxPool {
  312. return h.txpool
  313. }
  314. // ArchiveMode implements serverBackend
  315. func (h *serverHandler) ArchiveMode() bool {
  316. return h.server.archiveMode
  317. }
  318. // AddTxsSync implements serverBackend
  319. func (h *serverHandler) AddTxsSync() bool {
  320. return h.addTxsSync
  321. }
  322. // getAccount retrieves an account from the state based on root.
  323. func getAccount(triedb *trie.Database, root, hash common.Hash) (state.Account, error) {
  324. trie, err := trie.New(root, triedb)
  325. if err != nil {
  326. return state.Account{}, err
  327. }
  328. blob, err := trie.TryGet(hash[:])
  329. if err != nil {
  330. return state.Account{}, err
  331. }
  332. var account state.Account
  333. if err = rlp.DecodeBytes(blob, &account); err != nil {
  334. return state.Account{}, err
  335. }
  336. return account, nil
  337. }
  338. // getHelperTrie returns the post-processed trie root for the given trie ID and section index
  339. func (h *serverHandler) GetHelperTrie(typ uint, index uint64) *trie.Trie {
  340. var (
  341. root common.Hash
  342. prefix string
  343. )
  344. switch typ {
  345. case htCanonical:
  346. sectionHead := rawdb.ReadCanonicalHash(h.chainDb, (index+1)*h.server.iConfig.ChtSize-1)
  347. root, prefix = light.GetChtRoot(h.chainDb, index, sectionHead), light.ChtTablePrefix
  348. case htBloomBits:
  349. sectionHead := rawdb.ReadCanonicalHash(h.chainDb, (index+1)*h.server.iConfig.BloomTrieSize-1)
  350. root, prefix = light.GetBloomTrieRoot(h.chainDb, index, sectionHead), light.BloomTrieTablePrefix
  351. }
  352. if root == (common.Hash{}) {
  353. return nil
  354. }
  355. trie, _ := trie.New(root, trie.NewDatabase(rawdb.NewTable(h.chainDb, prefix)))
  356. return trie
  357. }
  358. // broadcastLoop broadcasts new block information to all connected light
  359. // clients. According to the agreement between client and server, server should
  360. // only broadcast new announcement if the total difficulty is higher than the
  361. // last one. Besides server will add the signature if client requires.
  362. func (h *serverHandler) broadcastLoop() {
  363. defer h.wg.Done()
  364. headCh := make(chan core.ChainHeadEvent, 10)
  365. headSub := h.blockchain.SubscribeChainHeadEvent(headCh)
  366. defer headSub.Unsubscribe()
  367. var (
  368. lastHead *types.Header
  369. lastTd = common.Big0
  370. )
  371. for {
  372. select {
  373. case ev := <-headCh:
  374. header := ev.Block.Header()
  375. hash, number := header.Hash(), header.Number.Uint64()
  376. td := h.blockchain.GetTd(hash, number)
  377. if td == nil || td.Cmp(lastTd) <= 0 {
  378. continue
  379. }
  380. var reorg uint64
  381. if lastHead != nil {
  382. reorg = lastHead.Number.Uint64() - rawdb.FindCommonAncestor(h.chainDb, header, lastHead).Number.Uint64()
  383. }
  384. lastHead, lastTd = header, td
  385. log.Debug("Announcing block to peers", "number", number, "hash", hash, "td", td, "reorg", reorg)
  386. h.server.broadcaster.broadcast(announceData{Hash: hash, Number: number, Td: td, ReorgDepth: reorg})
  387. case <-h.closeCh:
  388. return
  389. }
  390. }
  391. }
  392. // broadcaster sends new header announcements to active client peers
  393. type broadcaster struct {
  394. ns *nodestate.NodeStateMachine
  395. privateKey *ecdsa.PrivateKey
  396. lastAnnounce, signedAnnounce announceData
  397. }
  398. // newBroadcaster creates a new broadcaster
  399. func newBroadcaster(ns *nodestate.NodeStateMachine) *broadcaster {
  400. b := &broadcaster{ns: ns}
  401. ns.SubscribeState(priorityPoolSetup.ActiveFlag, func(node *enode.Node, oldState, newState nodestate.Flags) {
  402. if newState.Equals(priorityPoolSetup.ActiveFlag) {
  403. // send last announcement to activated peers
  404. b.sendTo(node)
  405. }
  406. })
  407. return b
  408. }
  409. // setSignerKey sets the signer key for signed announcements. Should be called before
  410. // starting the protocol handler.
  411. func (b *broadcaster) setSignerKey(privateKey *ecdsa.PrivateKey) {
  412. b.privateKey = privateKey
  413. }
  414. // broadcast sends the given announcements to all active peers
  415. func (b *broadcaster) broadcast(announce announceData) {
  416. b.ns.Operation(func() {
  417. // iterate in an Operation to ensure that the active set does not change while iterating
  418. b.lastAnnounce = announce
  419. b.ns.ForEach(priorityPoolSetup.ActiveFlag, nodestate.Flags{}, func(node *enode.Node, state nodestate.Flags) {
  420. b.sendTo(node)
  421. })
  422. })
  423. }
  424. // sendTo sends the most recent announcement to the given node unless the same or higher Td
  425. // announcement has already been sent.
  426. func (b *broadcaster) sendTo(node *enode.Node) {
  427. if b.lastAnnounce.Td == nil {
  428. return
  429. }
  430. if p, _ := b.ns.GetField(node, clientPeerField).(*clientPeer); p != nil {
  431. if p.headInfo.Td == nil || b.lastAnnounce.Td.Cmp(p.headInfo.Td) > 0 {
  432. announce := b.lastAnnounce
  433. switch p.announceType {
  434. case announceTypeSimple:
  435. if !p.queueSend(func() { p.sendAnnounce(announce) }) {
  436. log.Debug("Drop announcement because queue is full", "number", announce.Number, "hash", announce.Hash)
  437. } else {
  438. log.Debug("Sent announcement", "number", announce.Number, "hash", announce.Hash)
  439. }
  440. case announceTypeSigned:
  441. if b.signedAnnounce.Hash != b.lastAnnounce.Hash {
  442. b.signedAnnounce = b.lastAnnounce
  443. b.signedAnnounce.sign(b.privateKey)
  444. }
  445. announce := b.signedAnnounce
  446. if !p.queueSend(func() { p.sendAnnounce(announce) }) {
  447. log.Debug("Drop announcement because queue is full", "number", announce.Number, "hash", announce.Hash)
  448. } else {
  449. log.Debug("Sent announcement", "number", announce.Number, "hash", announce.Hash)
  450. }
  451. }
  452. p.headInfo = blockInfo{b.lastAnnounce.Hash, b.lastAnnounce.Number, b.lastAnnounce.Td}
  453. }
  454. }
  455. }