handler.go 30 KB

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