handler.go 27 KB

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