server_handler.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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. "encoding/binary"
  19. "encoding/json"
  20. "errors"
  21. "sync"
  22. "sync/atomic"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/common/mclock"
  26. "github.com/ethereum/go-ethereum/core"
  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. "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. ethVersion = 63 // equivalent eth version for the downloader
  42. MaxHeaderFetch = 192 // Amount of block headers to be fetched per retrieval request
  43. MaxBodyFetch = 32 // Amount of block bodies to be fetched per retrieval request
  44. MaxReceiptFetch = 128 // Amount of transaction receipts to allow fetching per request
  45. MaxCodeFetch = 64 // Amount of contract codes to allow fetching per request
  46. MaxProofsFetch = 64 // Amount of merkle proofs to be fetched per retrieval request
  47. MaxHelperTrieProofsFetch = 64 // Amount of helper tries to be fetched per retrieval request
  48. MaxTxSend = 64 // Amount of transactions to be send per request
  49. MaxTxStatus = 256 // Amount of transactions to queried per request
  50. )
  51. var (
  52. errTooManyInvalidRequest = errors.New("too many invalid requests made")
  53. errFullClientPool = errors.New("client pool is full")
  54. )
  55. // serverHandler is responsible for serving light client and process
  56. // all incoming light requests.
  57. type serverHandler struct {
  58. blockchain *core.BlockChain
  59. chainDb ethdb.Database
  60. txpool *core.TxPool
  61. server *LesServer
  62. closeCh chan struct{} // Channel used to exit all background routines of handler.
  63. wg sync.WaitGroup // WaitGroup used to track all background routines of handler.
  64. synced func() bool // Callback function used to determine whether local node is synced.
  65. // Testing fields
  66. addTxsSync bool
  67. }
  68. func newServerHandler(server *LesServer, blockchain *core.BlockChain, chainDb ethdb.Database, txpool *core.TxPool, synced func() bool) *serverHandler {
  69. handler := &serverHandler{
  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.broadcastHeaders()
  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. )
  106. if err := p.Handshake(td, hash, number, h.blockchain.Genesis().Hash(), h.server); err != nil {
  107. p.Log().Debug("Light Ethereum handshake failed", "err", err)
  108. return err
  109. }
  110. if p.server {
  111. // connected to another server, no messages expected, just wait for disconnection
  112. _, err := p.rw.ReadMsg()
  113. return err
  114. }
  115. // Reject light clients if server is not synced.
  116. if !h.synced() {
  117. p.Log().Debug("Light server not synced, rejecting peer")
  118. return p2p.DiscRequested
  119. }
  120. defer p.fcClient.Disconnect()
  121. // Disconnect the inbound peer if it's rejected by clientPool
  122. if !h.server.clientPool.connect(p, 0) {
  123. p.Log().Debug("Light Ethereum peer registration failed", "err", errFullClientPool)
  124. return errFullClientPool
  125. }
  126. // Register the peer locally
  127. if err := h.server.peers.register(p); err != nil {
  128. h.server.clientPool.disconnect(p)
  129. p.Log().Error("Light Ethereum peer registration failed", "err", err)
  130. return err
  131. }
  132. clientConnectionGauge.Update(int64(h.server.peers.len()))
  133. var wg sync.WaitGroup // Wait group used to track all in-flight task routines.
  134. connectedAt := mclock.Now()
  135. defer func() {
  136. wg.Wait() // Ensure all background task routines have exited.
  137. h.server.peers.unregister(p.id)
  138. h.server.clientPool.disconnect(p)
  139. clientConnectionGauge.Update(int64(h.server.peers.len()))
  140. connectionTimer.Update(time.Duration(mclock.Now() - connectedAt))
  141. }()
  142. // Spawn a main loop to handle all incoming messages.
  143. for {
  144. select {
  145. case err := <-p.errCh:
  146. p.Log().Debug("Failed to send light ethereum response", "err", err)
  147. return err
  148. default:
  149. }
  150. if err := h.handleMsg(p, &wg); err != nil {
  151. p.Log().Debug("Light Ethereum message handling failed", "err", err)
  152. return err
  153. }
  154. }
  155. }
  156. // handleMsg is invoked whenever an inbound message is received from a remote
  157. // peer. The remote connection is torn down upon returning any error.
  158. func (h *serverHandler) handleMsg(p *clientPeer, wg *sync.WaitGroup) error {
  159. // Read the next message from the remote peer, and ensure it's fully consumed
  160. msg, err := p.rw.ReadMsg()
  161. if err != nil {
  162. return err
  163. }
  164. p.Log().Trace("Light Ethereum message arrived", "code", msg.Code, "bytes", msg.Size)
  165. // Discard large message which exceeds the limitation.
  166. if msg.Size > ProtocolMaxMsgSize {
  167. clientErrorMeter.Mark(1)
  168. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  169. }
  170. defer msg.Discard()
  171. var (
  172. maxCost uint64
  173. task *servingTask
  174. )
  175. p.responseCount++
  176. responseCount := p.responseCount
  177. // accept returns an indicator whether the request can be served.
  178. // If so, deduct the max cost from the flow control buffer.
  179. accept := func(reqID, reqCnt, maxCnt uint64) bool {
  180. // Short circuit if the peer is already frozen or the request is invalid.
  181. inSizeCost := h.server.costTracker.realCost(0, msg.Size, 0)
  182. if p.isFrozen() || reqCnt == 0 || reqCnt > maxCnt {
  183. p.fcClient.OneTimeCost(inSizeCost)
  184. return false
  185. }
  186. // Prepaid max cost units before request been serving.
  187. maxCost = p.fcCosts.getMaxCost(msg.Code, reqCnt)
  188. accepted, bufShort, priority := p.fcClient.AcceptRequest(reqID, responseCount, maxCost)
  189. if !accepted {
  190. p.freeze()
  191. p.Log().Error("Request came too early", "remaining", common.PrettyDuration(time.Duration(bufShort*1000000/p.fcParams.MinRecharge)))
  192. p.fcClient.OneTimeCost(inSizeCost)
  193. return false
  194. }
  195. // Create a multi-stage task, estimate the time it takes for the task to
  196. // execute, and cache it in the request service queue.
  197. factor := h.server.costTracker.globalFactor()
  198. if factor < 0.001 {
  199. factor = 1
  200. p.Log().Error("Invalid global cost factor", "factor", factor)
  201. }
  202. maxTime := uint64(float64(maxCost) / factor)
  203. task = h.server.servingQueue.newTask(p, maxTime, priority)
  204. if task.start() {
  205. return true
  206. }
  207. p.fcClient.RequestProcessed(reqID, responseCount, maxCost, inSizeCost)
  208. return false
  209. }
  210. // sendResponse sends back the response and updates the flow control statistic.
  211. sendResponse := func(reqID, amount uint64, reply *reply, servingTime uint64) {
  212. p.responseLock.Lock()
  213. defer p.responseLock.Unlock()
  214. // Short circuit if the client is already frozen.
  215. if p.isFrozen() {
  216. realCost := h.server.costTracker.realCost(servingTime, msg.Size, 0)
  217. p.fcClient.RequestProcessed(reqID, responseCount, maxCost, realCost)
  218. return
  219. }
  220. // Positive correction buffer value with real cost.
  221. var replySize uint32
  222. if reply != nil {
  223. replySize = reply.size()
  224. }
  225. var realCost uint64
  226. if h.server.costTracker.testing {
  227. realCost = maxCost // Assign a fake cost for testing purpose
  228. } else {
  229. realCost = h.server.costTracker.realCost(servingTime, msg.Size, replySize)
  230. }
  231. bv := p.fcClient.RequestProcessed(reqID, responseCount, maxCost, realCost)
  232. if amount != 0 {
  233. // Feed cost tracker request serving statistic.
  234. h.server.costTracker.updateStats(msg.Code, amount, servingTime, realCost)
  235. // Reduce priority "balance" for the specific peer.
  236. h.server.clientPool.requestCost(p, realCost)
  237. }
  238. if reply != nil {
  239. p.mustQueueSend(func() {
  240. if err := reply.send(bv); err != nil {
  241. select {
  242. case p.errCh <- err:
  243. default:
  244. }
  245. }
  246. })
  247. }
  248. }
  249. switch msg.Code {
  250. case GetBlockHeadersMsg:
  251. p.Log().Trace("Received block header request")
  252. if metrics.EnabledExpensive {
  253. miscInHeaderPacketsMeter.Mark(1)
  254. miscInHeaderTrafficMeter.Mark(int64(msg.Size))
  255. }
  256. var req struct {
  257. ReqID uint64
  258. Query getBlockHeadersData
  259. }
  260. if err := msg.Decode(&req); err != nil {
  261. clientErrorMeter.Mark(1)
  262. return errResp(ErrDecode, "%v: %v", msg, err)
  263. }
  264. query := req.Query
  265. if accept(req.ReqID, query.Amount, MaxHeaderFetch) {
  266. wg.Add(1)
  267. go func() {
  268. defer wg.Done()
  269. hashMode := query.Origin.Hash != (common.Hash{})
  270. first := true
  271. maxNonCanonical := uint64(100)
  272. // Gather headers until the fetch or network limits is reached
  273. var (
  274. bytes common.StorageSize
  275. headers []*types.Header
  276. unknown bool
  277. )
  278. for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit {
  279. if !first && !task.waitOrStop() {
  280. sendResponse(req.ReqID, 0, nil, task.servingTime)
  281. return
  282. }
  283. // Retrieve the next header satisfying the query
  284. var origin *types.Header
  285. if hashMode {
  286. if first {
  287. origin = h.blockchain.GetHeaderByHash(query.Origin.Hash)
  288. if origin != nil {
  289. query.Origin.Number = origin.Number.Uint64()
  290. }
  291. } else {
  292. origin = h.blockchain.GetHeader(query.Origin.Hash, query.Origin.Number)
  293. }
  294. } else {
  295. origin = h.blockchain.GetHeaderByNumber(query.Origin.Number)
  296. }
  297. if origin == nil {
  298. atomic.AddUint32(&p.invalidCount, 1)
  299. break
  300. }
  301. headers = append(headers, origin)
  302. bytes += estHeaderRlpSize
  303. // Advance to the next header of the query
  304. switch {
  305. case hashMode && query.Reverse:
  306. // Hash based traversal towards the genesis block
  307. ancestor := query.Skip + 1
  308. if ancestor == 0 {
  309. unknown = true
  310. } else {
  311. query.Origin.Hash, query.Origin.Number = h.blockchain.GetAncestor(query.Origin.Hash, query.Origin.Number, ancestor, &maxNonCanonical)
  312. unknown = query.Origin.Hash == common.Hash{}
  313. }
  314. case hashMode && !query.Reverse:
  315. // Hash based traversal towards the leaf block
  316. var (
  317. current = origin.Number.Uint64()
  318. next = current + query.Skip + 1
  319. )
  320. if next <= current {
  321. infos, _ := json.MarshalIndent(p.Peer.Info(), "", " ")
  322. p.Log().Warn("GetBlockHeaders skip overflow attack", "current", current, "skip", query.Skip, "next", next, "attacker", infos)
  323. unknown = true
  324. } else {
  325. if header := h.blockchain.GetHeaderByNumber(next); header != nil {
  326. nextHash := header.Hash()
  327. expOldHash, _ := h.blockchain.GetAncestor(nextHash, next, query.Skip+1, &maxNonCanonical)
  328. if expOldHash == query.Origin.Hash {
  329. query.Origin.Hash, query.Origin.Number = nextHash, next
  330. } else {
  331. unknown = true
  332. }
  333. } else {
  334. unknown = true
  335. }
  336. }
  337. case query.Reverse:
  338. // Number based traversal towards the genesis block
  339. if query.Origin.Number >= query.Skip+1 {
  340. query.Origin.Number -= query.Skip + 1
  341. } else {
  342. unknown = true
  343. }
  344. case !query.Reverse:
  345. // Number based traversal towards the leaf block
  346. query.Origin.Number += query.Skip + 1
  347. }
  348. first = false
  349. }
  350. reply := p.replyBlockHeaders(req.ReqID, headers)
  351. sendResponse(req.ReqID, query.Amount, p.replyBlockHeaders(req.ReqID, headers), task.done())
  352. if metrics.EnabledExpensive {
  353. miscOutHeaderPacketsMeter.Mark(1)
  354. miscOutHeaderTrafficMeter.Mark(int64(reply.size()))
  355. miscServingTimeHeaderTimer.Update(time.Duration(task.servingTime))
  356. }
  357. }()
  358. }
  359. case GetBlockBodiesMsg:
  360. p.Log().Trace("Received block bodies request")
  361. if metrics.EnabledExpensive {
  362. miscInBodyPacketsMeter.Mark(1)
  363. miscInBodyTrafficMeter.Mark(int64(msg.Size))
  364. }
  365. var req struct {
  366. ReqID uint64
  367. Hashes []common.Hash
  368. }
  369. if err := msg.Decode(&req); err != nil {
  370. clientErrorMeter.Mark(1)
  371. return errResp(ErrDecode, "msg %v: %v", msg, err)
  372. }
  373. var (
  374. bytes int
  375. bodies []rlp.RawValue
  376. )
  377. reqCnt := len(req.Hashes)
  378. if accept(req.ReqID, uint64(reqCnt), MaxBodyFetch) {
  379. wg.Add(1)
  380. go func() {
  381. defer wg.Done()
  382. for i, hash := range req.Hashes {
  383. if i != 0 && !task.waitOrStop() {
  384. sendResponse(req.ReqID, 0, nil, task.servingTime)
  385. return
  386. }
  387. if bytes >= softResponseLimit {
  388. break
  389. }
  390. body := h.blockchain.GetBodyRLP(hash)
  391. if body == nil {
  392. atomic.AddUint32(&p.invalidCount, 1)
  393. continue
  394. }
  395. bodies = append(bodies, body)
  396. bytes += len(body)
  397. }
  398. reply := p.replyBlockBodiesRLP(req.ReqID, bodies)
  399. sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
  400. if metrics.EnabledExpensive {
  401. miscOutBodyPacketsMeter.Mark(1)
  402. miscOutBodyTrafficMeter.Mark(int64(reply.size()))
  403. miscServingTimeBodyTimer.Update(time.Duration(task.servingTime))
  404. }
  405. }()
  406. }
  407. case GetCodeMsg:
  408. p.Log().Trace("Received code request")
  409. if metrics.EnabledExpensive {
  410. miscInCodePacketsMeter.Mark(1)
  411. miscInCodeTrafficMeter.Mark(int64(msg.Size))
  412. }
  413. var req struct {
  414. ReqID uint64
  415. Reqs []CodeReq
  416. }
  417. if err := msg.Decode(&req); err != nil {
  418. clientErrorMeter.Mark(1)
  419. return errResp(ErrDecode, "msg %v: %v", msg, err)
  420. }
  421. var (
  422. bytes int
  423. data [][]byte
  424. )
  425. reqCnt := len(req.Reqs)
  426. if accept(req.ReqID, uint64(reqCnt), MaxCodeFetch) {
  427. wg.Add(1)
  428. go func() {
  429. defer wg.Done()
  430. for i, request := range req.Reqs {
  431. if i != 0 && !task.waitOrStop() {
  432. sendResponse(req.ReqID, 0, nil, task.servingTime)
  433. return
  434. }
  435. // Look up the root hash belonging to the request
  436. header := h.blockchain.GetHeaderByHash(request.BHash)
  437. if header == nil {
  438. p.Log().Warn("Failed to retrieve associate header for code", "hash", request.BHash)
  439. atomic.AddUint32(&p.invalidCount, 1)
  440. continue
  441. }
  442. // Refuse to search stale state data in the database since looking for
  443. // a non-exist key is kind of expensive.
  444. local := h.blockchain.CurrentHeader().Number.Uint64()
  445. if !h.server.archiveMode && header.Number.Uint64()+core.TriesInMemory <= local {
  446. p.Log().Debug("Reject stale code request", "number", header.Number.Uint64(), "head", local)
  447. atomic.AddUint32(&p.invalidCount, 1)
  448. continue
  449. }
  450. triedb := h.blockchain.StateCache().TrieDB()
  451. account, err := h.getAccount(triedb, header.Root, common.BytesToHash(request.AccKey))
  452. if err != nil {
  453. p.Log().Warn("Failed to retrieve account for code", "block", header.Number, "hash", header.Hash(), "account", common.BytesToHash(request.AccKey), "err", err)
  454. atomic.AddUint32(&p.invalidCount, 1)
  455. continue
  456. }
  457. code, err := triedb.Node(common.BytesToHash(account.CodeHash))
  458. if err != nil {
  459. p.Log().Warn("Failed to retrieve account code", "block", header.Number, "hash", header.Hash(), "account", common.BytesToHash(request.AccKey), "codehash", common.BytesToHash(account.CodeHash), "err", err)
  460. continue
  461. }
  462. // Accumulate the code and abort if enough data was retrieved
  463. data = append(data, code)
  464. if bytes += len(code); bytes >= softResponseLimit {
  465. break
  466. }
  467. }
  468. reply := p.replyCode(req.ReqID, data)
  469. sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
  470. if metrics.EnabledExpensive {
  471. miscOutCodePacketsMeter.Mark(1)
  472. miscOutCodeTrafficMeter.Mark(int64(reply.size()))
  473. miscServingTimeCodeTimer.Update(time.Duration(task.servingTime))
  474. }
  475. }()
  476. }
  477. case GetReceiptsMsg:
  478. p.Log().Trace("Received receipts request")
  479. if metrics.EnabledExpensive {
  480. miscInReceiptPacketsMeter.Mark(1)
  481. miscInReceiptTrafficMeter.Mark(int64(msg.Size))
  482. }
  483. var req struct {
  484. ReqID uint64
  485. Hashes []common.Hash
  486. }
  487. if err := msg.Decode(&req); err != nil {
  488. clientErrorMeter.Mark(1)
  489. return errResp(ErrDecode, "msg %v: %v", msg, err)
  490. }
  491. var (
  492. bytes int
  493. receipts []rlp.RawValue
  494. )
  495. reqCnt := len(req.Hashes)
  496. if accept(req.ReqID, uint64(reqCnt), MaxReceiptFetch) {
  497. wg.Add(1)
  498. go func() {
  499. defer wg.Done()
  500. for i, hash := range req.Hashes {
  501. if i != 0 && !task.waitOrStop() {
  502. sendResponse(req.ReqID, 0, nil, task.servingTime)
  503. return
  504. }
  505. if bytes >= softResponseLimit {
  506. break
  507. }
  508. // Retrieve the requested block's receipts, skipping if unknown to us
  509. results := h.blockchain.GetReceiptsByHash(hash)
  510. if results == nil {
  511. if header := h.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
  512. atomic.AddUint32(&p.invalidCount, 1)
  513. continue
  514. }
  515. }
  516. // If known, encode and queue for response packet
  517. if encoded, err := rlp.EncodeToBytes(results); err != nil {
  518. log.Error("Failed to encode receipt", "err", err)
  519. } else {
  520. receipts = append(receipts, encoded)
  521. bytes += len(encoded)
  522. }
  523. }
  524. reply := p.replyReceiptsRLP(req.ReqID, receipts)
  525. sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
  526. if metrics.EnabledExpensive {
  527. miscOutReceiptPacketsMeter.Mark(1)
  528. miscOutReceiptTrafficMeter.Mark(int64(reply.size()))
  529. miscServingTimeReceiptTimer.Update(time.Duration(task.servingTime))
  530. }
  531. }()
  532. }
  533. case GetProofsV2Msg:
  534. p.Log().Trace("Received les/2 proofs request")
  535. if metrics.EnabledExpensive {
  536. miscInTrieProofPacketsMeter.Mark(1)
  537. miscInTrieProofTrafficMeter.Mark(int64(msg.Size))
  538. }
  539. var req struct {
  540. ReqID uint64
  541. Reqs []ProofReq
  542. }
  543. if err := msg.Decode(&req); err != nil {
  544. clientErrorMeter.Mark(1)
  545. return errResp(ErrDecode, "msg %v: %v", msg, err)
  546. }
  547. // Gather state data until the fetch or network limits is reached
  548. var (
  549. lastBHash common.Hash
  550. root common.Hash
  551. )
  552. reqCnt := len(req.Reqs)
  553. if accept(req.ReqID, uint64(reqCnt), MaxProofsFetch) {
  554. wg.Add(1)
  555. go func() {
  556. defer wg.Done()
  557. nodes := light.NewNodeSet()
  558. for i, request := range req.Reqs {
  559. if i != 0 && !task.waitOrStop() {
  560. sendResponse(req.ReqID, 0, nil, task.servingTime)
  561. return
  562. }
  563. // Look up the root hash belonging to the request
  564. var (
  565. header *types.Header
  566. trie state.Trie
  567. )
  568. if request.BHash != lastBHash {
  569. root, lastBHash = common.Hash{}, request.BHash
  570. if header = h.blockchain.GetHeaderByHash(request.BHash); header == nil {
  571. p.Log().Warn("Failed to retrieve header for proof", "hash", request.BHash)
  572. atomic.AddUint32(&p.invalidCount, 1)
  573. continue
  574. }
  575. // Refuse to search stale state data in the database since looking for
  576. // a non-exist key is kind of expensive.
  577. local := h.blockchain.CurrentHeader().Number.Uint64()
  578. if !h.server.archiveMode && header.Number.Uint64()+core.TriesInMemory <= local {
  579. p.Log().Debug("Reject stale trie request", "number", header.Number.Uint64(), "head", local)
  580. atomic.AddUint32(&p.invalidCount, 1)
  581. continue
  582. }
  583. root = header.Root
  584. }
  585. // If a header lookup failed (non existent), ignore subsequent requests for the same header
  586. if root == (common.Hash{}) {
  587. atomic.AddUint32(&p.invalidCount, 1)
  588. continue
  589. }
  590. // Open the account or storage trie for the request
  591. statedb := h.blockchain.StateCache()
  592. switch len(request.AccKey) {
  593. case 0:
  594. // No account key specified, open an account trie
  595. trie, err = statedb.OpenTrie(root)
  596. if trie == nil || err != nil {
  597. p.Log().Warn("Failed to open storage trie for proof", "block", header.Number, "hash", header.Hash(), "root", root, "err", err)
  598. continue
  599. }
  600. default:
  601. // Account key specified, open a storage trie
  602. account, err := h.getAccount(statedb.TrieDB(), root, common.BytesToHash(request.AccKey))
  603. if err != nil {
  604. p.Log().Warn("Failed to retrieve account for proof", "block", header.Number, "hash", header.Hash(), "account", common.BytesToHash(request.AccKey), "err", err)
  605. atomic.AddUint32(&p.invalidCount, 1)
  606. continue
  607. }
  608. trie, err = statedb.OpenStorageTrie(common.BytesToHash(request.AccKey), account.Root)
  609. if trie == nil || err != nil {
  610. p.Log().Warn("Failed to open storage trie for proof", "block", header.Number, "hash", header.Hash(), "account", common.BytesToHash(request.AccKey), "root", account.Root, "err", err)
  611. continue
  612. }
  613. }
  614. // Prove the user's request from the account or stroage trie
  615. if err := trie.Prove(request.Key, request.FromLevel, nodes); err != nil {
  616. p.Log().Warn("Failed to prove state request", "block", header.Number, "hash", header.Hash(), "err", err)
  617. continue
  618. }
  619. if nodes.DataSize() >= softResponseLimit {
  620. break
  621. }
  622. }
  623. reply := p.replyProofsV2(req.ReqID, nodes.NodeList())
  624. sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
  625. if metrics.EnabledExpensive {
  626. miscOutTrieProofPacketsMeter.Mark(1)
  627. miscOutTrieProofTrafficMeter.Mark(int64(reply.size()))
  628. miscServingTimeTrieProofTimer.Update(time.Duration(task.servingTime))
  629. }
  630. }()
  631. }
  632. case GetHelperTrieProofsMsg:
  633. p.Log().Trace("Received helper trie proof request")
  634. if metrics.EnabledExpensive {
  635. miscInHelperTriePacketsMeter.Mark(1)
  636. miscInHelperTrieTrafficMeter.Mark(int64(msg.Size))
  637. }
  638. var req struct {
  639. ReqID uint64
  640. Reqs []HelperTrieReq
  641. }
  642. if err := msg.Decode(&req); err != nil {
  643. clientErrorMeter.Mark(1)
  644. return errResp(ErrDecode, "msg %v: %v", msg, err)
  645. }
  646. // Gather state data until the fetch or network limits is reached
  647. var (
  648. auxBytes int
  649. auxData [][]byte
  650. )
  651. reqCnt := len(req.Reqs)
  652. if accept(req.ReqID, uint64(reqCnt), MaxHelperTrieProofsFetch) {
  653. wg.Add(1)
  654. go func() {
  655. defer wg.Done()
  656. var (
  657. lastIdx uint64
  658. lastType uint
  659. root common.Hash
  660. auxTrie *trie.Trie
  661. )
  662. nodes := light.NewNodeSet()
  663. for i, request := range req.Reqs {
  664. if i != 0 && !task.waitOrStop() {
  665. sendResponse(req.ReqID, 0, nil, task.servingTime)
  666. return
  667. }
  668. if auxTrie == nil || request.Type != lastType || request.TrieIdx != lastIdx {
  669. auxTrie, lastType, lastIdx = nil, request.Type, request.TrieIdx
  670. var prefix string
  671. if root, prefix = h.getHelperTrie(request.Type, request.TrieIdx); root != (common.Hash{}) {
  672. auxTrie, _ = trie.New(root, trie.NewDatabase(rawdb.NewTable(h.chainDb, prefix)))
  673. }
  674. }
  675. if request.AuxReq == auxRoot {
  676. var data []byte
  677. if root != (common.Hash{}) {
  678. data = root[:]
  679. }
  680. auxData = append(auxData, data)
  681. auxBytes += len(data)
  682. } else {
  683. if auxTrie != nil {
  684. auxTrie.Prove(request.Key, request.FromLevel, nodes)
  685. }
  686. if request.AuxReq != 0 {
  687. data := h.getAuxiliaryHeaders(request)
  688. auxData = append(auxData, data)
  689. auxBytes += len(data)
  690. }
  691. }
  692. if nodes.DataSize()+auxBytes >= softResponseLimit {
  693. break
  694. }
  695. }
  696. reply := p.replyHelperTrieProofs(req.ReqID, HelperTrieResps{Proofs: nodes.NodeList(), AuxData: auxData})
  697. sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
  698. if metrics.EnabledExpensive {
  699. miscOutHelperTriePacketsMeter.Mark(1)
  700. miscOutHelperTrieTrafficMeter.Mark(int64(reply.size()))
  701. miscServingTimeHelperTrieTimer.Update(time.Duration(task.servingTime))
  702. }
  703. }()
  704. }
  705. case SendTxV2Msg:
  706. p.Log().Trace("Received new transactions")
  707. if metrics.EnabledExpensive {
  708. miscInTxsPacketsMeter.Mark(1)
  709. miscInTxsTrafficMeter.Mark(int64(msg.Size))
  710. }
  711. var req struct {
  712. ReqID uint64
  713. Txs []*types.Transaction
  714. }
  715. if err := msg.Decode(&req); err != nil {
  716. clientErrorMeter.Mark(1)
  717. return errResp(ErrDecode, "msg %v: %v", msg, err)
  718. }
  719. reqCnt := len(req.Txs)
  720. if accept(req.ReqID, uint64(reqCnt), MaxTxSend) {
  721. wg.Add(1)
  722. go func() {
  723. defer wg.Done()
  724. stats := make([]light.TxStatus, len(req.Txs))
  725. for i, tx := range req.Txs {
  726. if i != 0 && !task.waitOrStop() {
  727. return
  728. }
  729. hash := tx.Hash()
  730. stats[i] = h.txStatus(hash)
  731. if stats[i].Status == core.TxStatusUnknown {
  732. addFn := h.txpool.AddRemotes
  733. // Add txs synchronously for testing purpose
  734. if h.addTxsSync {
  735. addFn = h.txpool.AddRemotesSync
  736. }
  737. if errs := addFn([]*types.Transaction{tx}); errs[0] != nil {
  738. stats[i].Error = errs[0].Error()
  739. continue
  740. }
  741. stats[i] = h.txStatus(hash)
  742. }
  743. }
  744. reply := p.replyTxStatus(req.ReqID, stats)
  745. sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
  746. if metrics.EnabledExpensive {
  747. miscOutTxsPacketsMeter.Mark(1)
  748. miscOutTxsTrafficMeter.Mark(int64(reply.size()))
  749. miscServingTimeTxTimer.Update(time.Duration(task.servingTime))
  750. }
  751. }()
  752. }
  753. case GetTxStatusMsg:
  754. p.Log().Trace("Received transaction status query request")
  755. if metrics.EnabledExpensive {
  756. miscInTxStatusPacketsMeter.Mark(1)
  757. miscInTxStatusTrafficMeter.Mark(int64(msg.Size))
  758. }
  759. var req struct {
  760. ReqID uint64
  761. Hashes []common.Hash
  762. }
  763. if err := msg.Decode(&req); err != nil {
  764. clientErrorMeter.Mark(1)
  765. return errResp(ErrDecode, "msg %v: %v", msg, err)
  766. }
  767. reqCnt := len(req.Hashes)
  768. if accept(req.ReqID, uint64(reqCnt), MaxTxStatus) {
  769. wg.Add(1)
  770. go func() {
  771. defer wg.Done()
  772. stats := make([]light.TxStatus, len(req.Hashes))
  773. for i, hash := range req.Hashes {
  774. if i != 0 && !task.waitOrStop() {
  775. sendResponse(req.ReqID, 0, nil, task.servingTime)
  776. return
  777. }
  778. stats[i] = h.txStatus(hash)
  779. }
  780. reply := p.replyTxStatus(req.ReqID, stats)
  781. sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
  782. if metrics.EnabledExpensive {
  783. miscOutTxStatusPacketsMeter.Mark(1)
  784. miscOutTxStatusTrafficMeter.Mark(int64(reply.size()))
  785. miscServingTimeTxStatusTimer.Update(time.Duration(task.servingTime))
  786. }
  787. }()
  788. }
  789. default:
  790. p.Log().Trace("Received invalid message", "code", msg.Code)
  791. clientErrorMeter.Mark(1)
  792. return errResp(ErrInvalidMsgCode, "%v", msg.Code)
  793. }
  794. // If the client has made too much invalid request(e.g. request a non-exist data),
  795. // reject them to prevent SPAM attack.
  796. if atomic.LoadUint32(&p.invalidCount) > maxRequestErrors {
  797. clientErrorMeter.Mark(1)
  798. return errTooManyInvalidRequest
  799. }
  800. return nil
  801. }
  802. // getAccount retrieves an account from the state based on root.
  803. func (h *serverHandler) getAccount(triedb *trie.Database, root, hash common.Hash) (state.Account, error) {
  804. trie, err := trie.New(root, triedb)
  805. if err != nil {
  806. return state.Account{}, err
  807. }
  808. blob, err := trie.TryGet(hash[:])
  809. if err != nil {
  810. return state.Account{}, err
  811. }
  812. var account state.Account
  813. if err = rlp.DecodeBytes(blob, &account); err != nil {
  814. return state.Account{}, err
  815. }
  816. return account, nil
  817. }
  818. // getHelperTrie returns the post-processed trie root for the given trie ID and section index
  819. func (h *serverHandler) getHelperTrie(typ uint, index uint64) (common.Hash, string) {
  820. switch typ {
  821. case htCanonical:
  822. sectionHead := rawdb.ReadCanonicalHash(h.chainDb, (index+1)*h.server.iConfig.ChtSize-1)
  823. return light.GetChtRoot(h.chainDb, index, sectionHead), light.ChtTablePrefix
  824. case htBloomBits:
  825. sectionHead := rawdb.ReadCanonicalHash(h.chainDb, (index+1)*h.server.iConfig.BloomTrieSize-1)
  826. return light.GetBloomTrieRoot(h.chainDb, index, sectionHead), light.BloomTrieTablePrefix
  827. }
  828. return common.Hash{}, ""
  829. }
  830. // getAuxiliaryHeaders returns requested auxiliary headers for the CHT request.
  831. func (h *serverHandler) getAuxiliaryHeaders(req HelperTrieReq) []byte {
  832. if req.Type == htCanonical && req.AuxReq == auxHeader && len(req.Key) == 8 {
  833. blockNum := binary.BigEndian.Uint64(req.Key)
  834. hash := rawdb.ReadCanonicalHash(h.chainDb, blockNum)
  835. return rawdb.ReadHeaderRLP(h.chainDb, hash, blockNum)
  836. }
  837. return nil
  838. }
  839. // txStatus returns the status of a specified transaction.
  840. func (h *serverHandler) txStatus(hash common.Hash) light.TxStatus {
  841. var stat light.TxStatus
  842. // Looking the transaction in txpool first.
  843. stat.Status = h.txpool.Status([]common.Hash{hash})[0]
  844. // If the transaction is unknown to the pool, try looking it up locally.
  845. if stat.Status == core.TxStatusUnknown {
  846. lookup := h.blockchain.GetTransactionLookup(hash)
  847. if lookup != nil {
  848. stat.Status = core.TxStatusIncluded
  849. stat.Lookup = lookup
  850. }
  851. }
  852. return stat
  853. }
  854. // broadcastHeaders broadcasts new block information to all connected light
  855. // clients. According to the agreement between client and server, server should
  856. // only broadcast new announcement if the total difficulty is higher than the
  857. // last one. Besides server will add the signature if client requires.
  858. func (h *serverHandler) broadcastHeaders() {
  859. defer h.wg.Done()
  860. headCh := make(chan core.ChainHeadEvent, 10)
  861. headSub := h.blockchain.SubscribeChainHeadEvent(headCh)
  862. defer headSub.Unsubscribe()
  863. var (
  864. lastHead *types.Header
  865. lastTd = common.Big0
  866. )
  867. for {
  868. select {
  869. case ev := <-headCh:
  870. peers := h.server.peers.allPeers()
  871. if len(peers) == 0 {
  872. continue
  873. }
  874. header := ev.Block.Header()
  875. hash, number := header.Hash(), header.Number.Uint64()
  876. td := h.blockchain.GetTd(hash, number)
  877. if td == nil || td.Cmp(lastTd) <= 0 {
  878. continue
  879. }
  880. var reorg uint64
  881. if lastHead != nil {
  882. reorg = lastHead.Number.Uint64() - rawdb.FindCommonAncestor(h.chainDb, header, lastHead).Number.Uint64()
  883. }
  884. lastHead, lastTd = header, td
  885. log.Debug("Announcing block to peers", "number", number, "hash", hash, "td", td, "reorg", reorg)
  886. var (
  887. signed bool
  888. signedAnnounce announceData
  889. )
  890. announce := announceData{Hash: hash, Number: number, Td: td, ReorgDepth: reorg}
  891. for _, p := range peers {
  892. p := p
  893. switch p.announceType {
  894. case announceTypeSimple:
  895. if !p.queueSend(func() { p.sendAnnounce(announce) }) {
  896. log.Debug("Drop announcement because queue is full", "number", number, "hash", hash)
  897. }
  898. case announceTypeSigned:
  899. if !signed {
  900. signedAnnounce = announce
  901. signedAnnounce.sign(h.server.privateKey)
  902. signed = true
  903. }
  904. if !p.queueSend(func() { p.sendAnnounce(signedAnnounce) }) {
  905. log.Debug("Drop announcement because queue is full", "number", number, "hash", hash)
  906. }
  907. }
  908. }
  909. case <-h.closeCh:
  910. return
  911. }
  912. }
  913. }