handler.go 26 KB

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