handler.go 32 KB

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