handler.go 33 KB

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