handler.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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. directBroadcast bool
  61. checkpointNumber uint64 // Block number for the sync progress validator to cross reference
  62. checkpointHash common.Hash // Block hash for the sync progress validator to cross reference
  63. txpool txPool
  64. blockchain *core.BlockChain
  65. maxPeers int
  66. downloader *downloader.Downloader
  67. blockFetcher *fetcher.BlockFetcher
  68. txFetcher *fetcher.TxFetcher
  69. peers *peerSet
  70. eventMux *event.TypeMux
  71. txsCh chan core.NewTxsEvent
  72. txsSub event.Subscription
  73. minedBlockSub *event.TypeMuxSubscription
  74. whitelist map[uint64]common.Hash
  75. // channels for fetcher, syncer, txsyncLoop
  76. txsyncCh chan *txsync
  77. quitSync chan struct{}
  78. chainSync *chainSyncer
  79. wg sync.WaitGroup
  80. peerWG sync.WaitGroup
  81. // Test fields or hooks
  82. broadcastTxAnnouncesOnly bool // Testing field, disable transaction propagation
  83. }
  84. // NewProtocolManager returns a new Ethereum sub protocol manager. The Ethereum sub protocol manages peers capable
  85. // with the Ethereum network.
  86. 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, directBroadcast bool) (*ProtocolManager, error) {
  87. // Create the protocol manager with the base fields
  88. manager := &ProtocolManager{
  89. directBroadcast: directBroadcast,
  90. networkID: networkID,
  91. forkFilter: forkid.NewFilter(blockchain),
  92. eventMux: mux,
  93. txpool: txpool,
  94. blockchain: blockchain,
  95. peers: newPeerSet(),
  96. whitelist: whitelist,
  97. txsyncCh: make(chan *txsync),
  98. quitSync: make(chan struct{}),
  99. }
  100. if mode == downloader.FullSync {
  101. // The database seems empty as the current block is the genesis. Yet the fast
  102. // block is ahead, so fast sync was enabled for this node at a certain point.
  103. // The scenarios where this can happen is
  104. // * if the user manually (or via a bad block) rolled back a fast sync node
  105. // below the sync point.
  106. // * the last fast sync is not finished while user specifies a full sync this
  107. // time. But we don't have any recent state for full sync.
  108. // In these cases however it's safe to reenable fast sync.
  109. fullBlock, fastBlock := blockchain.CurrentBlock(), blockchain.CurrentFastBlock()
  110. if fullBlock.NumberU64() == 0 && fastBlock.NumberU64() > 0 {
  111. manager.fastSync = uint32(1)
  112. log.Warn("Switch sync mode from full sync to fast sync")
  113. }
  114. } else {
  115. if blockchain.CurrentBlock().NumberU64() > 0 {
  116. // Print warning log if database is not empty to run fast sync.
  117. log.Warn("Switch sync mode from fast sync to full sync")
  118. } else {
  119. // If fast sync was requested and our database is empty, grant it
  120. manager.fastSync = uint32(1)
  121. }
  122. }
  123. // If we have trusted checkpoints, enforce them on the chain
  124. if checkpoint != nil {
  125. manager.checkpointNumber = (checkpoint.SectionIndex+1)*params.CHTFrequency - 1
  126. manager.checkpointHash = checkpoint.SectionHead
  127. }
  128. // Construct the downloader (long sync) and its backing state bloom if fast
  129. // sync is requested. The downloader is responsible for deallocating the state
  130. // bloom when it's done.
  131. var stateBloom *trie.SyncBloom
  132. if atomic.LoadUint32(&manager.fastSync) == 1 {
  133. stateBloom = trie.NewSyncBloom(uint64(cacheLimit), chaindb)
  134. }
  135. manager.downloader = downloader.New(manager.checkpointNumber, chaindb, stateBloom, manager.eventMux, blockchain, nil, manager.removePeer)
  136. // Construct the fetcher (short sync)
  137. validator := func(header *types.Header) error {
  138. return engine.VerifyHeader(blockchain, header, true)
  139. }
  140. heighter := func() uint64 {
  141. return blockchain.CurrentBlock().NumberU64()
  142. }
  143. inserter := func(blocks types.Blocks) (int, error) {
  144. // If sync hasn't reached the checkpoint yet, deny importing weird blocks.
  145. //
  146. // Ideally we would also compare the head block's timestamp and similarly reject
  147. // the propagated block if the head is too old. Unfortunately there is a corner
  148. // case when starting new networks, where the genesis might be ancient (0 unix)
  149. // which would prevent full nodes from accepting it.
  150. if manager.blockchain.CurrentBlock().NumberU64() < manager.checkpointNumber {
  151. log.Warn("Unsynced yet, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
  152. return 0, nil
  153. }
  154. // If fast sync is running, deny importing weird blocks. This is a problematic
  155. // clause when starting up a new network, because fast-syncing miners might not
  156. // accept each others' blocks until a restart. Unfortunately we haven't figured
  157. // out a way yet where nodes can decide unilaterally whether the network is new
  158. // or not. This should be fixed if we figure out a solution.
  159. if atomic.LoadUint32(&manager.fastSync) == 1 {
  160. log.Warn("Fast syncing, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
  161. return 0, nil
  162. }
  163. n, err := manager.blockchain.InsertChain(blocks)
  164. if err == nil {
  165. atomic.StoreUint32(&manager.acceptTxs, 1) // Mark initial sync done on any fetcher import
  166. }
  167. return n, err
  168. }
  169. manager.blockFetcher = fetcher.NewBlockFetcher(blockchain.GetBlockByHash, validator, manager.BroadcastBlock, heighter, inserter, manager.removePeer)
  170. fetchTx := func(peer string, hashes []common.Hash) error {
  171. p := manager.peers.Peer(peer)
  172. if p == nil {
  173. return errors.New("unknown peer")
  174. }
  175. return p.RequestTxs(hashes)
  176. }
  177. manager.txFetcher = fetcher.NewTxFetcher(txpool.Has, txpool.AddRemotes, fetchTx)
  178. manager.chainSync = newChainSyncer(manager)
  179. return manager, nil
  180. }
  181. func (pm *ProtocolManager) makeProtocol(version uint) p2p.Protocol {
  182. length, ok := protocolLengths[version]
  183. if !ok {
  184. panic("makeProtocol for unknown version")
  185. }
  186. return p2p.Protocol{
  187. Name: protocolName,
  188. Version: version,
  189. Length: length,
  190. Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
  191. return pm.runPeer(pm.newPeer(int(version), p, rw, pm.txpool.Get))
  192. },
  193. NodeInfo: func() interface{} {
  194. return pm.NodeInfo()
  195. },
  196. PeerInfo: func(id enode.ID) interface{} {
  197. if p := pm.peers.Peer(fmt.Sprintf("%x", id[:8])); p != nil {
  198. return p.Info()
  199. }
  200. return nil
  201. },
  202. }
  203. }
  204. func (pm *ProtocolManager) removePeer(id string) {
  205. // Short circuit if the peer was already removed
  206. peer := pm.peers.Peer(id)
  207. if peer == nil {
  208. return
  209. }
  210. log.Debug("Removing Ethereum peer", "peer", id)
  211. // Unregister the peer from the downloader and Ethereum peer set
  212. pm.downloader.UnregisterPeer(id)
  213. pm.txFetcher.Drop(id)
  214. if err := pm.peers.Unregister(id); err != nil {
  215. log.Error("Peer removal failed", "peer", id, "err", err)
  216. }
  217. // Hard disconnect at the networking layer
  218. if peer != nil {
  219. peer.Peer.Disconnect(p2p.DiscUselessPeer)
  220. }
  221. }
  222. func (pm *ProtocolManager) Start(maxPeers int) {
  223. pm.maxPeers = maxPeers
  224. // broadcast transactions
  225. pm.wg.Add(1)
  226. pm.txsCh = make(chan core.NewTxsEvent, txChanSize)
  227. pm.txsSub = pm.txpool.SubscribeNewTxsEvent(pm.txsCh)
  228. go pm.txBroadcastLoop()
  229. // broadcast mined blocks
  230. pm.wg.Add(1)
  231. pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
  232. go pm.minedBroadcastLoop()
  233. // start sync handlers
  234. pm.wg.Add(2)
  235. go pm.chainSync.loop()
  236. go pm.txsyncLoop64() // TODO(karalabe): Legacy initial tx echange, drop with eth/64.
  237. }
  238. func (pm *ProtocolManager) Stop() {
  239. pm.txsSub.Unsubscribe() // quits txBroadcastLoop
  240. pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
  241. // Quit chainSync and txsync64.
  242. // After this is done, no new peers will be accepted.
  243. close(pm.quitSync)
  244. pm.wg.Wait()
  245. // Disconnect existing sessions.
  246. // This also closes the gate for any new registrations on the peer set.
  247. // sessions which are already established but not added to pm.peers yet
  248. // will exit when they try to register.
  249. pm.peers.Close()
  250. pm.peerWG.Wait()
  251. log.Info("Ethereum protocol stopped")
  252. }
  253. func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter, getPooledTx func(hash common.Hash) *types.Transaction) *peer {
  254. return newPeer(pv, p, rw, getPooledTx)
  255. }
  256. func (pm *ProtocolManager) runPeer(p *peer) error {
  257. if !pm.chainSync.handlePeerEvent(p) {
  258. return p2p.DiscQuitting
  259. }
  260. pm.peerWG.Add(1)
  261. defer pm.peerWG.Done()
  262. return pm.handle(p)
  263. }
  264. // handle is the callback invoked to manage the life cycle of an eth peer. When
  265. // this function terminates, the peer is disconnected.
  266. func (pm *ProtocolManager) handle(p *peer) error {
  267. // Ignore maxPeers if this is a trusted peer
  268. if pm.peers.Len() >= pm.maxPeers && !p.Peer.Info().Network.Trusted {
  269. return p2p.DiscTooManyPeers
  270. }
  271. p.Log().Debug("Ethereum peer connected", "name", p.Name())
  272. // Execute the Ethereum handshake
  273. var (
  274. genesis = pm.blockchain.Genesis()
  275. head = pm.blockchain.CurrentHeader()
  276. hash = head.Hash()
  277. number = head.Number.Uint64()
  278. td = pm.blockchain.GetTd(hash, number)
  279. )
  280. if err := p.Handshake(pm.networkID, td, hash, genesis.Hash(), forkid.NewID(pm.blockchain), pm.forkFilter); err != nil {
  281. p.Log().Debug("Ethereum handshake failed", "err", err)
  282. return err
  283. }
  284. // Register the peer locally
  285. if err := pm.peers.Register(p); err != nil {
  286. p.Log().Error("Ethereum peer registration failed", "err", err)
  287. return err
  288. }
  289. defer pm.removePeer(p.id)
  290. // Register the peer in the downloader. If the downloader considers it banned, we disconnect
  291. if err := pm.downloader.RegisterPeer(p.id, p.version, p); err != nil {
  292. return err
  293. }
  294. pm.chainSync.handlePeerEvent(p)
  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. pm.chainSync.handlePeerEvent(p)
  664. }
  665. case msg.Code == NewPooledTransactionHashesMsg && p.version >= eth65:
  666. // New transaction announcement arrived, make sure we have
  667. // a valid and fresh chain to handle them
  668. if atomic.LoadUint32(&pm.acceptTxs) == 0 {
  669. break
  670. }
  671. var hashes []common.Hash
  672. if err := msg.Decode(&hashes); err != nil {
  673. return errResp(ErrDecode, "msg %v: %v", msg, err)
  674. }
  675. // Schedule all the unknown hashes for retrieval
  676. for _, hash := range hashes {
  677. p.MarkTransaction(hash)
  678. }
  679. pm.txFetcher.Notify(p.id, hashes)
  680. case msg.Code == GetPooledTransactionsMsg && p.version >= eth65:
  681. // Decode the retrieval message
  682. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  683. if _, err := msgStream.List(); err != nil {
  684. return err
  685. }
  686. // Gather transactions until the fetch or network limits is reached
  687. var (
  688. hash common.Hash
  689. bytes int
  690. hashes []common.Hash
  691. txs []rlp.RawValue
  692. )
  693. for bytes < softResponseLimit {
  694. // Retrieve the hash of the next block
  695. if err := msgStream.Decode(&hash); err == rlp.EOL {
  696. break
  697. } else if err != nil {
  698. return errResp(ErrDecode, "msg %v: %v", msg, err)
  699. }
  700. // Retrieve the requested transaction, skipping if unknown to us
  701. tx := pm.txpool.Get(hash)
  702. if tx == nil {
  703. continue
  704. }
  705. // If known, encode and queue for response packet
  706. if encoded, err := rlp.EncodeToBytes(tx); err != nil {
  707. log.Error("Failed to encode transaction", "err", err)
  708. } else {
  709. hashes = append(hashes, hash)
  710. txs = append(txs, encoded)
  711. bytes += len(encoded)
  712. }
  713. }
  714. return p.SendPooledTransactionsRLP(hashes, txs)
  715. case msg.Code == TransactionMsg || (msg.Code == PooledTransactionsMsg && p.version >= eth65):
  716. // Transactions arrived, make sure we have a valid and fresh chain to handle them
  717. if atomic.LoadUint32(&pm.acceptTxs) == 0 {
  718. break
  719. }
  720. // Transactions can be processed, parse all of them and deliver to the pool
  721. var txs []*types.Transaction
  722. if err := msg.Decode(&txs); err != nil {
  723. return errResp(ErrDecode, "msg %v: %v", msg, err)
  724. }
  725. for i, tx := range txs {
  726. // Validate and mark the remote transaction
  727. if tx == nil {
  728. return errResp(ErrDecode, "transaction %d is nil", i)
  729. }
  730. p.MarkTransaction(tx.Hash())
  731. }
  732. pm.txFetcher.Enqueue(p.id, txs, msg.Code == PooledTransactionsMsg)
  733. default:
  734. return errResp(ErrInvalidMsgCode, "%v", msg.Code)
  735. }
  736. return nil
  737. }
  738. // BroadcastBlock will either propagate a block to a subset of its peers, or
  739. // will only announce its availability (depending what's requested).
  740. func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
  741. hash := block.Hash()
  742. peers := pm.peers.PeersWithoutBlock(hash)
  743. // If propagation is requested, send to a subset of the peer
  744. if propagate {
  745. // Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
  746. var td *big.Int
  747. if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
  748. td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1))
  749. } else {
  750. log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
  751. return
  752. }
  753. // Send the block to a subset of our peers
  754. var transfer []*peer
  755. if pm.directBroadcast {
  756. transfer = peers[:int(len(peers))]
  757. } else {
  758. transfer = peers[:int(math.Sqrt(float64(len(peers))))]
  759. }
  760. for _, peer := range transfer {
  761. peer.AsyncSendNewBlock(block, td)
  762. }
  763. log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  764. return
  765. }
  766. // Otherwise if the block is indeed in out own chain, announce it
  767. if pm.blockchain.HasBlock(hash, block.NumberU64()) {
  768. for _, peer := range peers {
  769. peer.AsyncSendNewBlockHash(block)
  770. }
  771. log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  772. }
  773. }
  774. // BroadcastTransactions will propagate a batch of transactions to all peers which are not known to
  775. // already have the given transaction.
  776. func (pm *ProtocolManager) BroadcastTransactions(txs types.Transactions, propagate bool) {
  777. var (
  778. txset = make(map[*peer][]common.Hash)
  779. annos = make(map[*peer][]common.Hash)
  780. )
  781. // Broadcast transactions to a batch of peers not knowing about it
  782. if propagate {
  783. for _, tx := range txs {
  784. peers := pm.peers.PeersWithoutTx(tx.Hash())
  785. // Send the block to a subset of our peers
  786. transfer := peers[:int(math.Sqrt(float64(len(peers))))]
  787. for _, peer := range transfer {
  788. txset[peer] = append(txset[peer], tx.Hash())
  789. }
  790. log.Trace("Broadcast transaction", "hash", tx.Hash(), "recipients", len(peers))
  791. }
  792. for peer, hashes := range txset {
  793. peer.AsyncSendTransactions(hashes)
  794. }
  795. return
  796. }
  797. // Otherwise only broadcast the announcement to peers
  798. for _, tx := range txs {
  799. peers := pm.peers.PeersWithoutTx(tx.Hash())
  800. for _, peer := range peers {
  801. annos[peer] = append(annos[peer], tx.Hash())
  802. }
  803. }
  804. for peer, hashes := range annos {
  805. if peer.version >= eth65 {
  806. peer.AsyncSendPooledTransactionHashes(hashes)
  807. } else {
  808. peer.AsyncSendTransactions(hashes)
  809. }
  810. }
  811. }
  812. // minedBroadcastLoop sends mined blocks to connected peers.
  813. func (pm *ProtocolManager) minedBroadcastLoop() {
  814. defer pm.wg.Done()
  815. for obj := range pm.minedBlockSub.Chan() {
  816. if ev, ok := obj.Data.(core.NewMinedBlockEvent); ok {
  817. pm.BroadcastBlock(ev.Block, true) // First propagate block to peers
  818. pm.BroadcastBlock(ev.Block, false) // Only then announce to the rest
  819. }
  820. }
  821. }
  822. // txBroadcastLoop announces new transactions to connected peers.
  823. func (pm *ProtocolManager) txBroadcastLoop() {
  824. defer pm.wg.Done()
  825. for {
  826. select {
  827. case event := <-pm.txsCh:
  828. // For testing purpose only, disable propagation
  829. if pm.broadcastTxAnnouncesOnly {
  830. pm.BroadcastTransactions(event.Txs, false)
  831. continue
  832. }
  833. pm.BroadcastTransactions(event.Txs, true) // First propagate transactions to peers
  834. pm.BroadcastTransactions(event.Txs, false) // Only then announce to the rest
  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. }