handler.go 29 KB

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