handler.go 29 KB

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