handler.go 29 KB

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