handler.go 28 KB

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