handler.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. // Copyright 2015 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 eth
  17. import (
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "math"
  22. "math/big"
  23. "sync"
  24. "sync/atomic"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/consensus"
  28. "github.com/ethereum/go-ethereum/consensus/misc"
  29. "github.com/ethereum/go-ethereum/core"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/eth/downloader"
  32. "github.com/ethereum/go-ethereum/eth/fetcher"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/event"
  35. "github.com/ethereum/go-ethereum/log"
  36. "github.com/ethereum/go-ethereum/p2p"
  37. "github.com/ethereum/go-ethereum/p2p/discover"
  38. "github.com/ethereum/go-ethereum/params"
  39. "github.com/ethereum/go-ethereum/rlp"
  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. )
  45. var (
  46. daoChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the DAO handshake challenge
  47. )
  48. // errIncompatibleConfig is returned if the requested protocols and configs are
  49. // not compatible (low protocol version restrictions and high requirements).
  50. var errIncompatibleConfig = errors.New("incompatible configuration")
  51. func errResp(code errCode, format string, v ...interface{}) error {
  52. return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...))
  53. }
  54. type ProtocolManager struct {
  55. networkId uint64
  56. fastSync uint32 // Flag whether fast sync is enabled (gets disabled if we already have blocks)
  57. acceptTxs uint32 // Flag whether we're considered synchronised (enables transaction processing)
  58. txpool txPool
  59. blockchain *core.BlockChain
  60. chaindb ethdb.Database
  61. chainconfig *params.ChainConfig
  62. maxPeers int
  63. downloader *downloader.Downloader
  64. fetcher *fetcher.Fetcher
  65. peers *peerSet
  66. SubProtocols []p2p.Protocol
  67. eventMux *event.TypeMux
  68. txSub *event.TypeMuxSubscription
  69. minedBlockSub *event.TypeMuxSubscription
  70. // channels for fetcher, syncer, txsyncLoop
  71. newPeerCh chan *peer
  72. txsyncCh chan *txsync
  73. quitSync chan struct{}
  74. noMorePeers chan struct{}
  75. lesServer LesServer
  76. // wait group is used for graceful shutdowns during downloading
  77. // and processing
  78. wg sync.WaitGroup
  79. }
  80. // NewProtocolManager returns a new ethereum sub protocol manager. The Ethereum sub protocol manages peers capable
  81. // with the ethereum network.
  82. func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, networkId uint64, maxPeers int, mux *event.TypeMux, txpool txPool, engine consensus.Engine, blockchain *core.BlockChain, chaindb ethdb.Database) (*ProtocolManager, error) {
  83. // Create the protocol manager with the base fields
  84. manager := &ProtocolManager{
  85. networkId: networkId,
  86. eventMux: mux,
  87. txpool: txpool,
  88. blockchain: blockchain,
  89. chaindb: chaindb,
  90. chainconfig: config,
  91. maxPeers: maxPeers,
  92. peers: newPeerSet(),
  93. newPeerCh: make(chan *peer),
  94. noMorePeers: make(chan struct{}),
  95. txsyncCh: make(chan *txsync),
  96. quitSync: make(chan struct{}),
  97. }
  98. // Figure out whether to allow fast sync or not
  99. if mode == downloader.FastSync && blockchain.CurrentBlock().NumberU64() > 0 {
  100. log.Warn("Blockchain not empty, fast sync disabled")
  101. mode = downloader.FullSync
  102. }
  103. if mode == downloader.FastSync {
  104. manager.fastSync = uint32(1)
  105. }
  106. // Initiate a sub-protocol for every implemented version we can handle
  107. manager.SubProtocols = make([]p2p.Protocol, 0, len(ProtocolVersions))
  108. for i, version := range ProtocolVersions {
  109. // Skip protocol version if incompatible with the mode of operation
  110. if mode == downloader.FastSync && version < eth63 {
  111. continue
  112. }
  113. // Compatible; initialise the sub-protocol
  114. version := version // Closure for the run
  115. manager.SubProtocols = append(manager.SubProtocols, p2p.Protocol{
  116. Name: ProtocolName,
  117. Version: version,
  118. Length: ProtocolLengths[i],
  119. Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
  120. peer := manager.newPeer(int(version), p, rw)
  121. select {
  122. case manager.newPeerCh <- peer:
  123. manager.wg.Add(1)
  124. defer manager.wg.Done()
  125. return manager.handle(peer)
  126. case <-manager.quitSync:
  127. return p2p.DiscQuitting
  128. }
  129. },
  130. NodeInfo: func() interface{} {
  131. return manager.NodeInfo()
  132. },
  133. PeerInfo: func(id discover.NodeID) interface{} {
  134. if p := manager.peers.Peer(fmt.Sprintf("%x", id[:8])); p != nil {
  135. return p.Info()
  136. }
  137. return nil
  138. },
  139. })
  140. }
  141. if len(manager.SubProtocols) == 0 {
  142. return nil, errIncompatibleConfig
  143. }
  144. // Construct the different synchronisation mechanisms
  145. manager.downloader = downloader.New(mode, chaindb, manager.eventMux, blockchain.HasHeader, blockchain.HasBlockAndState, blockchain.GetHeaderByHash,
  146. blockchain.GetBlockByHash, blockchain.CurrentHeader, blockchain.CurrentBlock, blockchain.CurrentFastBlock, blockchain.FastSyncCommitHead,
  147. blockchain.GetTdByHash, blockchain.InsertHeaderChain, manager.blockchain.InsertChain, blockchain.InsertReceiptChain, blockchain.Rollback,
  148. manager.removePeer)
  149. validator := func(header *types.Header) error {
  150. return engine.VerifyHeader(blockchain, header, true)
  151. }
  152. heighter := func() uint64 {
  153. return blockchain.CurrentBlock().NumberU64()
  154. }
  155. inserter := func(blocks types.Blocks) (int, error) {
  156. // If fast sync is running, deny importing weird blocks
  157. if atomic.LoadUint32(&manager.fastSync) == 1 {
  158. log.Warn("Discarded bad propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
  159. return 0, nil
  160. }
  161. atomic.StoreUint32(&manager.acceptTxs, 1) // Mark initial sync done on any fetcher import
  162. return manager.blockchain.InsertChain(blocks)
  163. }
  164. manager.fetcher = fetcher.New(blockchain.GetBlockByHash, validator, manager.BroadcastBlock, heighter, inserter, manager.removePeer)
  165. return manager, nil
  166. }
  167. func (pm *ProtocolManager) removePeer(id string) {
  168. // Short circuit if the peer was already removed
  169. peer := pm.peers.Peer(id)
  170. if peer == nil {
  171. return
  172. }
  173. log.Debug("Removing Ethereum peer", "peer", id)
  174. // Unregister the peer from the downloader and Ethereum peer set
  175. pm.downloader.UnregisterPeer(id)
  176. if err := pm.peers.Unregister(id); err != nil {
  177. log.Error("Peer removal failed", "peer", id, "err", err)
  178. }
  179. // Hard disconnect at the networking layer
  180. if peer != nil {
  181. peer.Peer.Disconnect(p2p.DiscUselessPeer)
  182. }
  183. }
  184. func (pm *ProtocolManager) Start() {
  185. // broadcast transactions
  186. pm.txSub = pm.eventMux.Subscribe(core.TxPreEvent{})
  187. go pm.txBroadcastLoop()
  188. // broadcast mined blocks
  189. pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
  190. go pm.minedBroadcastLoop()
  191. // start sync handlers
  192. go pm.syncer()
  193. go pm.txsyncLoop()
  194. }
  195. func (pm *ProtocolManager) Stop() {
  196. log.Info("Stopping Ethereum protocol")
  197. pm.txSub.Unsubscribe() // quits txBroadcastLoop
  198. pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
  199. // Quit the sync loop.
  200. // After this send has completed, no new peers will be accepted.
  201. pm.noMorePeers <- struct{}{}
  202. // Quit fetcher, txsyncLoop.
  203. close(pm.quitSync)
  204. // Disconnect existing sessions.
  205. // This also closes the gate for any new registrations on the peer set.
  206. // sessions which are already established but not added to pm.peers yet
  207. // will exit when they try to register.
  208. pm.peers.Close()
  209. // Wait for all peer handler goroutines and the loops to come down.
  210. pm.wg.Wait()
  211. log.Info("Ethereum protocol stopped")
  212. }
  213. func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
  214. return newPeer(pv, p, newMeteredMsgWriter(rw))
  215. }
  216. // handle is the callback invoked to manage the life cycle of an eth peer. When
  217. // this function terminates, the peer is disconnected.
  218. func (pm *ProtocolManager) handle(p *peer) error {
  219. if pm.peers.Len() >= pm.maxPeers {
  220. return p2p.DiscTooManyPeers
  221. }
  222. p.Log().Debug("Ethereum peer connected", "name", p.Name())
  223. // Execute the Ethereum handshake
  224. td, head, genesis := pm.blockchain.Status()
  225. if err := p.Handshake(pm.networkId, td, head, genesis); err != nil {
  226. p.Log().Debug("Ethereum handshake failed", "err", err)
  227. return err
  228. }
  229. if rw, ok := p.rw.(*meteredMsgReadWriter); ok {
  230. rw.Init(p.version)
  231. }
  232. // Register the peer locally
  233. if err := pm.peers.Register(p); err != nil {
  234. p.Log().Error("Ethereum peer registration failed", "err", err)
  235. return err
  236. }
  237. defer pm.removePeer(p.id)
  238. // Register the peer in the downloader. If the downloader considers it banned, we disconnect
  239. if err := pm.downloader.RegisterPeer(p.id, p.version, p.Head, p.RequestHeadersByHash, p.RequestHeadersByNumber, p.RequestBodies, p.RequestReceipts, p.RequestNodeData); err != nil {
  240. return err
  241. }
  242. // Propagate existing transactions. new transactions appearing
  243. // after this will be sent via broadcasts.
  244. pm.syncTransactions(p)
  245. // If we're DAO hard-fork aware, validate any remote peer with regard to the hard-fork
  246. if daoBlock := pm.chainconfig.DAOForkBlock; daoBlock != nil {
  247. // Request the peer's DAO fork header for extra-data validation
  248. if err := p.RequestHeadersByNumber(daoBlock.Uint64(), 1, 0, false); err != nil {
  249. return err
  250. }
  251. // Start a timer to disconnect if the peer doesn't reply in time
  252. p.forkDrop = time.AfterFunc(daoChallengeTimeout, func() {
  253. p.Log().Debug("Timed out DAO fork-check, dropping")
  254. pm.removePeer(p.id)
  255. })
  256. // Make sure it's cleaned up if the peer dies off
  257. defer func() {
  258. if p.forkDrop != nil {
  259. p.forkDrop.Stop()
  260. p.forkDrop = nil
  261. }
  262. }()
  263. }
  264. // main loop. handle incoming messages.
  265. for {
  266. if err := pm.handleMsg(p); err != nil {
  267. p.Log().Debug("Ethereum message handling failed", "err", err)
  268. return err
  269. }
  270. }
  271. }
  272. // handleMsg is invoked whenever an inbound message is received from a remote
  273. // peer. The remote connection is torn down upon returning any error.
  274. func (pm *ProtocolManager) handleMsg(p *peer) error {
  275. // Read the next message from the remote peer, and ensure it's fully consumed
  276. msg, err := p.rw.ReadMsg()
  277. if err != nil {
  278. return err
  279. }
  280. if msg.Size > ProtocolMaxMsgSize {
  281. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  282. }
  283. defer msg.Discard()
  284. // Handle the message depending on its contents
  285. switch {
  286. case msg.Code == StatusMsg:
  287. // Status messages should never arrive after the handshake
  288. return errResp(ErrExtraStatusMsg, "uncontrolled status message")
  289. // Block header query, collect the requested headers and reply
  290. case msg.Code == GetBlockHeadersMsg:
  291. // Decode the complex header query
  292. var query getBlockHeadersData
  293. if err := msg.Decode(&query); err != nil {
  294. return errResp(ErrDecode, "%v: %v", msg, err)
  295. }
  296. hashMode := query.Origin.Hash != (common.Hash{})
  297. // Gather headers until the fetch or network limits is reached
  298. var (
  299. bytes common.StorageSize
  300. headers []*types.Header
  301. unknown bool
  302. )
  303. for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch {
  304. // Retrieve the next header satisfying the query
  305. var origin *types.Header
  306. if hashMode {
  307. origin = pm.blockchain.GetHeaderByHash(query.Origin.Hash)
  308. } else {
  309. origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
  310. }
  311. if origin == nil {
  312. break
  313. }
  314. number := origin.Number.Uint64()
  315. headers = append(headers, origin)
  316. bytes += estHeaderRlpSize
  317. // Advance to the next header of the query
  318. switch {
  319. case query.Origin.Hash != (common.Hash{}) && query.Reverse:
  320. // Hash based traversal towards the genesis block
  321. for i := 0; i < int(query.Skip)+1; i++ {
  322. if header := pm.blockchain.GetHeader(query.Origin.Hash, number); header != nil {
  323. query.Origin.Hash = header.ParentHash
  324. number--
  325. } else {
  326. unknown = true
  327. break
  328. }
  329. }
  330. case query.Origin.Hash != (common.Hash{}) && !query.Reverse:
  331. // Hash based traversal towards the leaf block
  332. var (
  333. current = origin.Number.Uint64()
  334. next = current + query.Skip + 1
  335. )
  336. if next <= current {
  337. infos, _ := json.MarshalIndent(p.Peer.Info(), "", " ")
  338. p.Log().Warn("GetBlockHeaders skip overflow attack", "current", current, "skip", query.Skip, "next", next, "attacker", infos)
  339. unknown = true
  340. } else {
  341. if header := pm.blockchain.GetHeaderByNumber(next); header != nil {
  342. if pm.blockchain.GetBlockHashesFromHash(header.Hash(), query.Skip+1)[query.Skip] == query.Origin.Hash {
  343. query.Origin.Hash = header.Hash()
  344. } else {
  345. unknown = true
  346. }
  347. } else {
  348. unknown = true
  349. }
  350. }
  351. case query.Reverse:
  352. // Number based traversal towards the genesis block
  353. if query.Origin.Number >= query.Skip+1 {
  354. query.Origin.Number -= (query.Skip + 1)
  355. } else {
  356. unknown = true
  357. }
  358. case !query.Reverse:
  359. // Number based traversal towards the leaf block
  360. query.Origin.Number += (query.Skip + 1)
  361. }
  362. }
  363. return p.SendBlockHeaders(headers)
  364. case msg.Code == BlockHeadersMsg:
  365. // A batch of headers arrived to one of our previous requests
  366. var headers []*types.Header
  367. if err := msg.Decode(&headers); err != nil {
  368. return errResp(ErrDecode, "msg %v: %v", msg, err)
  369. }
  370. // If no headers were received, but we're expending a DAO fork check, maybe it's that
  371. if len(headers) == 0 && p.forkDrop != nil {
  372. // Possibly an empty reply to the fork header checks, sanity check TDs
  373. verifyDAO := true
  374. // If we already have a DAO header, we can check the peer's TD against it. If
  375. // the peer's ahead of this, it too must have a reply to the DAO check
  376. if daoHeader := pm.blockchain.GetHeaderByNumber(pm.chainconfig.DAOForkBlock.Uint64()); daoHeader != nil {
  377. if _, td := p.Head(); td.Cmp(pm.blockchain.GetTd(daoHeader.Hash(), daoHeader.Number.Uint64())) >= 0 {
  378. verifyDAO = false
  379. }
  380. }
  381. // If we're seemingly on the same chain, disable the drop timer
  382. if verifyDAO {
  383. p.Log().Debug("Seems to be on the same side of the DAO fork")
  384. p.forkDrop.Stop()
  385. p.forkDrop = nil
  386. return nil
  387. }
  388. }
  389. // Filter out any explicitly requested headers, deliver the rest to the downloader
  390. filter := len(headers) == 1
  391. if filter {
  392. // If it's a potential DAO fork check, validate against the rules
  393. if p.forkDrop != nil && pm.chainconfig.DAOForkBlock.Cmp(headers[0].Number) == 0 {
  394. // Disable the fork drop timer
  395. p.forkDrop.Stop()
  396. p.forkDrop = nil
  397. // Validate the header and either drop the peer or continue
  398. if err := misc.VerifyDAOHeaderExtraData(pm.chainconfig, headers[0]); err != nil {
  399. p.Log().Debug("Verified to be on the other side of the DAO fork, dropping")
  400. return err
  401. }
  402. p.Log().Debug("Verified to be on the same side of the DAO fork")
  403. return nil
  404. }
  405. // Irrelevant of the fork checks, send the header to the fetcher just in case
  406. headers = pm.fetcher.FilterHeaders(headers, time.Now())
  407. }
  408. if len(headers) > 0 || !filter {
  409. err := pm.downloader.DeliverHeaders(p.id, headers)
  410. if err != nil {
  411. log.Debug("Failed to deliver headers", "err", err)
  412. }
  413. }
  414. case msg.Code == GetBlockBodiesMsg:
  415. // Decode the retrieval message
  416. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  417. if _, err := msgStream.List(); err != nil {
  418. return err
  419. }
  420. // Gather blocks until the fetch or network limits is reached
  421. var (
  422. hash common.Hash
  423. bytes int
  424. bodies []rlp.RawValue
  425. )
  426. for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch {
  427. // Retrieve the hash of the next block
  428. if err := msgStream.Decode(&hash); err == rlp.EOL {
  429. break
  430. } else if err != nil {
  431. return errResp(ErrDecode, "msg %v: %v", msg, err)
  432. }
  433. // Retrieve the requested block body, stopping if enough was found
  434. if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 {
  435. bodies = append(bodies, data)
  436. bytes += len(data)
  437. }
  438. }
  439. return p.SendBlockBodiesRLP(bodies)
  440. case msg.Code == BlockBodiesMsg:
  441. // A batch of block bodies arrived to one of our previous requests
  442. var request blockBodiesData
  443. if err := msg.Decode(&request); err != nil {
  444. return errResp(ErrDecode, "msg %v: %v", msg, err)
  445. }
  446. // Deliver them all to the downloader for queuing
  447. trasactions := make([][]*types.Transaction, len(request))
  448. uncles := make([][]*types.Header, len(request))
  449. for i, body := range request {
  450. trasactions[i] = body.Transactions
  451. uncles[i] = body.Uncles
  452. }
  453. // Filter out any explicitly requested bodies, deliver the rest to the downloader
  454. filter := len(trasactions) > 0 || len(uncles) > 0
  455. if filter {
  456. trasactions, uncles = pm.fetcher.FilterBodies(trasactions, uncles, time.Now())
  457. }
  458. if len(trasactions) > 0 || len(uncles) > 0 || !filter {
  459. err := pm.downloader.DeliverBodies(p.id, trasactions, uncles)
  460. if err != nil {
  461. log.Debug("Failed to deliver bodies", "err", err)
  462. }
  463. }
  464. case p.version >= eth63 && msg.Code == GetNodeDataMsg:
  465. // Decode the retrieval message
  466. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  467. if _, err := msgStream.List(); err != nil {
  468. return err
  469. }
  470. // Gather state data until the fetch or network limits is reached
  471. var (
  472. hash common.Hash
  473. bytes int
  474. data [][]byte
  475. )
  476. for bytes < softResponseLimit && len(data) < downloader.MaxStateFetch {
  477. // Retrieve the hash of the next state entry
  478. if err := msgStream.Decode(&hash); err == rlp.EOL {
  479. break
  480. } else if err != nil {
  481. return errResp(ErrDecode, "msg %v: %v", msg, err)
  482. }
  483. // Retrieve the requested state entry, stopping if enough was found
  484. if entry, err := pm.chaindb.Get(hash.Bytes()); err == nil {
  485. data = append(data, entry)
  486. bytes += len(entry)
  487. }
  488. }
  489. return p.SendNodeData(data)
  490. case p.version >= eth63 && msg.Code == NodeDataMsg:
  491. // A batch of node state data arrived to one of our previous requests
  492. var data [][]byte
  493. if err := msg.Decode(&data); err != nil {
  494. return errResp(ErrDecode, "msg %v: %v", msg, err)
  495. }
  496. // Deliver all to the downloader
  497. if err := pm.downloader.DeliverNodeData(p.id, data); err != nil {
  498. log.Debug("Failed to deliver node state data", "err", err)
  499. }
  500. case p.version >= eth63 && msg.Code == GetReceiptsMsg:
  501. // Decode the retrieval message
  502. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  503. if _, err := msgStream.List(); err != nil {
  504. return err
  505. }
  506. // Gather state data until the fetch or network limits is reached
  507. var (
  508. hash common.Hash
  509. bytes int
  510. receipts []rlp.RawValue
  511. )
  512. for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch {
  513. // Retrieve the hash of the next block
  514. if err := msgStream.Decode(&hash); err == rlp.EOL {
  515. break
  516. } else if err != nil {
  517. return errResp(ErrDecode, "msg %v: %v", msg, err)
  518. }
  519. // Retrieve the requested block's receipts, skipping if unknown to us
  520. results := core.GetBlockReceipts(pm.chaindb, hash, core.GetBlockNumber(pm.chaindb, hash))
  521. if results == nil {
  522. if header := pm.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
  523. continue
  524. }
  525. }
  526. // If known, encode and queue for response packet
  527. if encoded, err := rlp.EncodeToBytes(results); err != nil {
  528. log.Error("Failed to encode receipt", "err", err)
  529. } else {
  530. receipts = append(receipts, encoded)
  531. bytes += len(encoded)
  532. }
  533. }
  534. return p.SendReceiptsRLP(receipts)
  535. case p.version >= eth63 && msg.Code == ReceiptsMsg:
  536. // A batch of receipts arrived to one of our previous requests
  537. var receipts [][]*types.Receipt
  538. if err := msg.Decode(&receipts); err != nil {
  539. return errResp(ErrDecode, "msg %v: %v", msg, err)
  540. }
  541. // Deliver all to the downloader
  542. if err := pm.downloader.DeliverReceipts(p.id, receipts); err != nil {
  543. log.Debug("Failed to deliver receipts", "err", err)
  544. }
  545. case msg.Code == NewBlockHashesMsg:
  546. var announces newBlockHashesData
  547. if err := msg.Decode(&announces); err != nil {
  548. return errResp(ErrDecode, "%v: %v", msg, err)
  549. }
  550. // Mark the hashes as present at the remote node
  551. for _, block := range announces {
  552. p.MarkBlock(block.Hash)
  553. }
  554. // Schedule all the unknown hashes for retrieval
  555. unknown := make(newBlockHashesData, 0, len(announces))
  556. for _, block := range announces {
  557. if !pm.blockchain.HasBlock(block.Hash) {
  558. unknown = append(unknown, block)
  559. }
  560. }
  561. for _, block := range unknown {
  562. pm.fetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestOneHeader, p.RequestBodies)
  563. }
  564. case msg.Code == NewBlockMsg:
  565. // Retrieve and decode the propagated block
  566. var request newBlockData
  567. if err := msg.Decode(&request); err != nil {
  568. return errResp(ErrDecode, "%v: %v", msg, err)
  569. }
  570. request.Block.ReceivedAt = msg.ReceivedAt
  571. request.Block.ReceivedFrom = p
  572. // Mark the peer as owning the block and schedule it for import
  573. p.MarkBlock(request.Block.Hash())
  574. pm.fetcher.Enqueue(p.id, request.Block)
  575. // Assuming the block is importable by the peer, but possibly not yet done so,
  576. // calculate the head hash and TD that the peer truly must have.
  577. var (
  578. trueHead = request.Block.ParentHash()
  579. trueTD = new(big.Int).Sub(request.TD, request.Block.Difficulty())
  580. )
  581. // Update the peers total difficulty if better than the previous
  582. if _, td := p.Head(); trueTD.Cmp(td) > 0 {
  583. p.SetHead(trueHead, trueTD)
  584. // Schedule a sync if above ours. Note, this will not fire a sync for a gap of
  585. // a singe block (as the true TD is below the propagated block), however this
  586. // scenario should easily be covered by the fetcher.
  587. currentBlock := pm.blockchain.CurrentBlock()
  588. if trueTD.Cmp(pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64())) > 0 {
  589. go pm.synchronise(p)
  590. }
  591. }
  592. case msg.Code == TxMsg:
  593. // Transactions arrived, make sure we have a valid and fresh chain to handle them
  594. if atomic.LoadUint32(&pm.acceptTxs) == 0 {
  595. break
  596. }
  597. // Transactions can be processed, parse all of them and deliver to the pool
  598. var txs []*types.Transaction
  599. if err := msg.Decode(&txs); err != nil {
  600. return errResp(ErrDecode, "msg %v: %v", msg, err)
  601. }
  602. for i, tx := range txs {
  603. // Validate and mark the remote transaction
  604. if tx == nil {
  605. return errResp(ErrDecode, "transaction %d is nil", i)
  606. }
  607. p.MarkTransaction(tx.Hash())
  608. }
  609. pm.txpool.AddBatch(txs)
  610. default:
  611. return errResp(ErrInvalidMsgCode, "%v", msg.Code)
  612. }
  613. return nil
  614. }
  615. // BroadcastBlock will either propagate a block to a subset of it's peers, or
  616. // will only announce it's availability (depending what's requested).
  617. func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
  618. hash := block.Hash()
  619. peers := pm.peers.PeersWithoutBlock(hash)
  620. // If propagation is requested, send to a subset of the peer
  621. if propagate {
  622. // Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
  623. var td *big.Int
  624. if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
  625. td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1))
  626. } else {
  627. log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
  628. return
  629. }
  630. // Send the block to a subset of our peers
  631. transfer := peers[:int(math.Sqrt(float64(len(peers))))]
  632. for _, peer := range transfer {
  633. peer.SendNewBlock(block, td)
  634. }
  635. log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  636. }
  637. // Otherwise if the block is indeed in out own chain, announce it
  638. if pm.blockchain.HasBlock(hash) {
  639. for _, peer := range peers {
  640. peer.SendNewBlockHashes([]common.Hash{hash}, []uint64{block.NumberU64()})
  641. }
  642. log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  643. }
  644. }
  645. // BroadcastTx will propagate a transaction to all peers which are not known to
  646. // already have the given transaction.
  647. func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *types.Transaction) {
  648. // Broadcast transaction to a batch of peers not knowing about it
  649. peers := pm.peers.PeersWithoutTx(hash)
  650. //FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))]
  651. for _, peer := range peers {
  652. peer.SendTransactions(types.Transactions{tx})
  653. }
  654. log.Trace("Broadcast transaction", "hash", hash, "recipients", len(peers))
  655. }
  656. // Mined broadcast loop
  657. func (self *ProtocolManager) minedBroadcastLoop() {
  658. // automatically stops if unsubscribe
  659. for obj := range self.minedBlockSub.Chan() {
  660. switch ev := obj.Data.(type) {
  661. case core.NewMinedBlockEvent:
  662. self.BroadcastBlock(ev.Block, true) // First propagate block to peers
  663. self.BroadcastBlock(ev.Block, false) // Only then announce to the rest
  664. }
  665. }
  666. }
  667. func (self *ProtocolManager) txBroadcastLoop() {
  668. // automatically stops if unsubscribe
  669. for obj := range self.txSub.Chan() {
  670. event := obj.Data.(core.TxPreEvent)
  671. self.BroadcastTx(event.Tx.Hash(), event.Tx)
  672. }
  673. }
  674. // EthNodeInfo represents a short summary of the Ethereum sub-protocol metadata known
  675. // about the host peer.
  676. type EthNodeInfo struct {
  677. Network uint64 `json:"network"` // Ethereum network ID (1=Frontier, 2=Morden, Ropsten=3)
  678. Difficulty *big.Int `json:"difficulty"` // Total difficulty of the host's blockchain
  679. Genesis common.Hash `json:"genesis"` // SHA3 hash of the host's genesis block
  680. Head common.Hash `json:"head"` // SHA3 hash of the host's best owned block
  681. }
  682. // NodeInfo retrieves some protocol metadata about the running host node.
  683. func (self *ProtocolManager) NodeInfo() *EthNodeInfo {
  684. currentBlock := self.blockchain.CurrentBlock()
  685. return &EthNodeInfo{
  686. Network: self.networkId,
  687. Difficulty: self.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64()),
  688. Genesis: self.blockchain.Genesis().Hash(),
  689. Head: currentBlock.Hash(),
  690. }
  691. }