handler.go 26 KB

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