handler.go 26 KB

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