handler.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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. chaindb ethdb.Database
  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) (*ProtocolManager, error) {
  87. // Create the protocol manager with the base fields
  88. manager := &ProtocolManager{
  89. networkID: networkID,
  90. forkFilter: forkid.NewFilter(blockchain),
  91. eventMux: mux,
  92. txpool: txpool,
  93. blockchain: blockchain,
  94. chaindb: chaindb,
  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(false, nil, blockchain.GetBlockByHash, validator, manager.BroadcastBlock, heighter, nil, 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. forkID := forkid.NewID(pm.blockchain.Config(), pm.blockchain.Genesis().Hash(), pm.blockchain.CurrentHeader().Number.Uint64())
  281. if err := p.Handshake(pm.networkID, td, hash, genesis.Hash(), forkID, 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, pm.removePeer); 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. pm.chainSync.handlePeerEvent(p)
  296. // Propagate existing transactions. new transactions appearing
  297. // after this will be sent via broadcasts.
  298. pm.syncTransactions(p)
  299. // If we have a trusted CHT, reject all peers below that (avoid fast sync eclipse)
  300. if pm.checkpointHash != (common.Hash{}) {
  301. // Request the peer's checkpoint header for chain height/weight validation
  302. if err := p.RequestHeadersByNumber(pm.checkpointNumber, 1, 0, false); err != nil {
  303. return err
  304. }
  305. // Start a timer to disconnect if the peer doesn't reply in time
  306. p.syncDrop = time.AfterFunc(syncChallengeTimeout, func() {
  307. p.Log().Warn("Checkpoint challenge timed out, dropping", "addr", p.RemoteAddr(), "type", p.Name())
  308. pm.removePeer(p.id)
  309. })
  310. // Make sure it's cleaned up if the peer dies off
  311. defer func() {
  312. if p.syncDrop != nil {
  313. p.syncDrop.Stop()
  314. p.syncDrop = nil
  315. }
  316. }()
  317. }
  318. // If we have any explicit whitelist block hashes, request them
  319. for number := range pm.whitelist {
  320. if err := p.RequestHeadersByNumber(number, 1, 0, false); err != nil {
  321. return err
  322. }
  323. }
  324. // Handle incoming messages until the connection is torn down
  325. for {
  326. if err := pm.handleMsg(p); err != nil {
  327. p.Log().Debug("Ethereum message handling failed", "err", err)
  328. return err
  329. }
  330. }
  331. }
  332. // handleMsg is invoked whenever an inbound message is received from a remote
  333. // peer. The remote connection is torn down upon returning any error.
  334. func (pm *ProtocolManager) handleMsg(p *peer) error {
  335. // Read the next message from the remote peer, and ensure it's fully consumed
  336. msg, err := p.rw.ReadMsg()
  337. if err != nil {
  338. return err
  339. }
  340. if msg.Size > protocolMaxMsgSize {
  341. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, protocolMaxMsgSize)
  342. }
  343. defer msg.Discard()
  344. // Handle the message depending on its contents
  345. switch {
  346. case msg.Code == StatusMsg:
  347. // Status messages should never arrive after the handshake
  348. return errResp(ErrExtraStatusMsg, "uncontrolled status message")
  349. // Block header query, collect the requested headers and reply
  350. case msg.Code == GetBlockHeadersMsg:
  351. // Decode the complex header query
  352. var query getBlockHeadersData
  353. if err := msg.Decode(&query); err != nil {
  354. return errResp(ErrDecode, "%v: %v", msg, err)
  355. }
  356. hashMode := query.Origin.Hash != (common.Hash{})
  357. first := true
  358. maxNonCanonical := uint64(100)
  359. // Gather headers until the fetch or network limits is reached
  360. var (
  361. bytes common.StorageSize
  362. headers []*types.Header
  363. unknown bool
  364. )
  365. for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch {
  366. // Retrieve the next header satisfying the query
  367. var origin *types.Header
  368. if hashMode {
  369. if first {
  370. first = false
  371. origin = pm.blockchain.GetHeaderByHash(query.Origin.Hash)
  372. if origin != nil {
  373. query.Origin.Number = origin.Number.Uint64()
  374. }
  375. } else {
  376. origin = pm.blockchain.GetHeader(query.Origin.Hash, query.Origin.Number)
  377. }
  378. } else {
  379. origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
  380. }
  381. if origin == nil {
  382. break
  383. }
  384. headers = append(headers, origin)
  385. bytes += estHeaderRlpSize
  386. // Advance to the next header of the query
  387. switch {
  388. case hashMode && query.Reverse:
  389. // Hash based traversal towards the genesis block
  390. ancestor := query.Skip + 1
  391. if ancestor == 0 {
  392. unknown = true
  393. } else {
  394. query.Origin.Hash, query.Origin.Number = pm.blockchain.GetAncestor(query.Origin.Hash, query.Origin.Number, ancestor, &maxNonCanonical)
  395. unknown = (query.Origin.Hash == common.Hash{})
  396. }
  397. case hashMode && !query.Reverse:
  398. // Hash based traversal towards the leaf block
  399. var (
  400. current = origin.Number.Uint64()
  401. next = current + query.Skip + 1
  402. )
  403. if next <= current {
  404. infos, _ := json.MarshalIndent(p.Peer.Info(), "", " ")
  405. p.Log().Warn("GetBlockHeaders skip overflow attack", "current", current, "skip", query.Skip, "next", next, "attacker", infos)
  406. unknown = true
  407. } else {
  408. if header := pm.blockchain.GetHeaderByNumber(next); header != nil {
  409. nextHash := header.Hash()
  410. expOldHash, _ := pm.blockchain.GetAncestor(nextHash, next, query.Skip+1, &maxNonCanonical)
  411. if expOldHash == query.Origin.Hash {
  412. query.Origin.Hash, query.Origin.Number = nextHash, next
  413. } else {
  414. unknown = true
  415. }
  416. } else {
  417. unknown = true
  418. }
  419. }
  420. case query.Reverse:
  421. // Number based traversal towards the genesis block
  422. if query.Origin.Number >= query.Skip+1 {
  423. query.Origin.Number -= query.Skip + 1
  424. } else {
  425. unknown = true
  426. }
  427. case !query.Reverse:
  428. // Number based traversal towards the leaf block
  429. query.Origin.Number += query.Skip + 1
  430. }
  431. }
  432. return p.SendBlockHeaders(headers)
  433. case msg.Code == BlockHeadersMsg:
  434. // A batch of headers arrived to one of our previous requests
  435. var headers []*types.Header
  436. if err := msg.Decode(&headers); err != nil {
  437. return errResp(ErrDecode, "msg %v: %v", msg, err)
  438. }
  439. // If no headers were received, but we're expencting a checkpoint header, consider it that
  440. if len(headers) == 0 && p.syncDrop != nil {
  441. // Stop the timer either way, decide later to drop or not
  442. p.syncDrop.Stop()
  443. p.syncDrop = nil
  444. // If we're doing a fast sync, we must enforce the checkpoint block to avoid
  445. // eclipse attacks. Unsynced nodes are welcome to connect after we're done
  446. // joining the network
  447. if atomic.LoadUint32(&pm.fastSync) == 1 {
  448. p.Log().Warn("Dropping unsynced node during fast sync", "addr", p.RemoteAddr(), "type", p.Name())
  449. return errors.New("unsynced node cannot serve fast sync")
  450. }
  451. }
  452. // Filter out any explicitly requested headers, deliver the rest to the downloader
  453. filter := len(headers) == 1
  454. if filter {
  455. // If it's a potential sync progress check, validate the content and advertised chain weight
  456. if p.syncDrop != nil && headers[0].Number.Uint64() == pm.checkpointNumber {
  457. // Disable the sync drop timer
  458. p.syncDrop.Stop()
  459. p.syncDrop = nil
  460. // Validate the header and either drop the peer or continue
  461. if headers[0].Hash() != pm.checkpointHash {
  462. return errors.New("checkpoint hash mismatch")
  463. }
  464. return nil
  465. }
  466. // Otherwise if it's a whitelisted block, validate against the set
  467. if want, ok := pm.whitelist[headers[0].Number.Uint64()]; ok {
  468. if hash := headers[0].Hash(); want != hash {
  469. p.Log().Info("Whitelist mismatch, dropping peer", "number", headers[0].Number.Uint64(), "hash", hash, "want", want)
  470. return errors.New("whitelist block mismatch")
  471. }
  472. p.Log().Debug("Whitelist block verified", "number", headers[0].Number.Uint64(), "hash", want)
  473. }
  474. // Irrelevant of the fork checks, send the header to the fetcher just in case
  475. headers = pm.blockFetcher.FilterHeaders(p.id, headers, time.Now())
  476. }
  477. if len(headers) > 0 || !filter {
  478. err := pm.downloader.DeliverHeaders(p.id, headers)
  479. if err != nil {
  480. log.Debug("Failed to deliver headers", "err", err)
  481. }
  482. }
  483. case msg.Code == GetBlockBodiesMsg:
  484. // Decode the retrieval message
  485. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  486. if _, err := msgStream.List(); err != nil {
  487. return err
  488. }
  489. // Gather blocks until the fetch or network limits is reached
  490. var (
  491. hash common.Hash
  492. bytes int
  493. bodies []rlp.RawValue
  494. )
  495. for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch {
  496. // Retrieve the hash of the next block
  497. if err := msgStream.Decode(&hash); err == rlp.EOL {
  498. break
  499. } else if err != nil {
  500. return errResp(ErrDecode, "msg %v: %v", msg, err)
  501. }
  502. // Retrieve the requested block body, stopping if enough was found
  503. if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 {
  504. bodies = append(bodies, data)
  505. bytes += len(data)
  506. }
  507. }
  508. return p.SendBlockBodiesRLP(bodies)
  509. case msg.Code == BlockBodiesMsg:
  510. // A batch of block bodies arrived to one of our previous requests
  511. var request blockBodiesData
  512. if err := msg.Decode(&request); err != nil {
  513. return errResp(ErrDecode, "msg %v: %v", msg, err)
  514. }
  515. // Deliver them all to the downloader for queuing
  516. transactions := make([][]*types.Transaction, len(request))
  517. uncles := make([][]*types.Header, len(request))
  518. for i, body := range request {
  519. transactions[i] = body.Transactions
  520. uncles[i] = body.Uncles
  521. }
  522. // Filter out any explicitly requested bodies, deliver the rest to the downloader
  523. filter := len(transactions) > 0 || len(uncles) > 0
  524. if filter {
  525. transactions, uncles = pm.blockFetcher.FilterBodies(p.id, transactions, uncles, time.Now())
  526. }
  527. if len(transactions) > 0 || len(uncles) > 0 || !filter {
  528. err := pm.downloader.DeliverBodies(p.id, transactions, uncles)
  529. if err != nil {
  530. log.Debug("Failed to deliver bodies", "err", err)
  531. }
  532. }
  533. case p.version >= eth63 && msg.Code == GetNodeDataMsg:
  534. // Decode the retrieval message
  535. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  536. if _, err := msgStream.List(); err != nil {
  537. return err
  538. }
  539. // Gather state data until the fetch or network limits is reached
  540. var (
  541. hash common.Hash
  542. bytes int
  543. data [][]byte
  544. )
  545. for bytes < softResponseLimit && len(data) < downloader.MaxStateFetch {
  546. // Retrieve the hash of the next state entry
  547. if err := msgStream.Decode(&hash); err == rlp.EOL {
  548. break
  549. } else if err != nil {
  550. return errResp(ErrDecode, "msg %v: %v", msg, err)
  551. }
  552. // Retrieve the requested state entry, stopping if enough was found
  553. // todo now the code and trienode is mixed in the protocol level,
  554. // separate these two types.
  555. if !pm.downloader.SyncBloomContains(hash[:]) {
  556. // Only lookup the trie node if there's chance that we actually have it
  557. continue
  558. }
  559. entry, err := pm.blockchain.TrieNode(hash)
  560. if len(entry) == 0 || err != nil {
  561. // Read the contract code with prefix only to save unnecessary lookups.
  562. entry, err = pm.blockchain.ContractCodeWithPrefix(hash)
  563. }
  564. if err == nil && len(entry) > 0 {
  565. data = append(data, entry)
  566. bytes += len(entry)
  567. }
  568. }
  569. return p.SendNodeData(data)
  570. case p.version >= eth63 && msg.Code == NodeDataMsg:
  571. // A batch of node state data arrived to one of our previous requests
  572. var data [][]byte
  573. if err := msg.Decode(&data); err != nil {
  574. return errResp(ErrDecode, "msg %v: %v", msg, err)
  575. }
  576. // Deliver all to the downloader
  577. if err := pm.downloader.DeliverNodeData(p.id, data); err != nil {
  578. log.Debug("Failed to deliver node state data", "err", err)
  579. }
  580. case p.version >= eth63 && msg.Code == GetReceiptsMsg:
  581. // Decode the retrieval message
  582. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  583. if _, err := msgStream.List(); err != nil {
  584. return err
  585. }
  586. // Gather state data until the fetch or network limits is reached
  587. var (
  588. hash common.Hash
  589. bytes int
  590. receipts []rlp.RawValue
  591. )
  592. for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch {
  593. // Retrieve the hash of the next block
  594. if err := msgStream.Decode(&hash); err == rlp.EOL {
  595. break
  596. } else if err != nil {
  597. return errResp(ErrDecode, "msg %v: %v", msg, err)
  598. }
  599. // Retrieve the requested block's receipts, skipping if unknown to us
  600. results := pm.blockchain.GetReceiptsByHash(hash)
  601. if results == nil {
  602. if header := pm.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
  603. continue
  604. }
  605. }
  606. // If known, encode and queue for response packet
  607. if encoded, err := rlp.EncodeToBytes(results); err != nil {
  608. log.Error("Failed to encode receipt", "err", err)
  609. } else {
  610. receipts = append(receipts, encoded)
  611. bytes += len(encoded)
  612. }
  613. }
  614. return p.SendReceiptsRLP(receipts)
  615. case p.version >= eth63 && msg.Code == ReceiptsMsg:
  616. // A batch of receipts arrived to one of our previous requests
  617. var receipts [][]*types.Receipt
  618. if err := msg.Decode(&receipts); err != nil {
  619. return errResp(ErrDecode, "msg %v: %v", msg, err)
  620. }
  621. // Deliver all to the downloader
  622. if err := pm.downloader.DeliverReceipts(p.id, receipts); err != nil {
  623. log.Debug("Failed to deliver receipts", "err", err)
  624. }
  625. case msg.Code == NewBlockHashesMsg:
  626. var announces newBlockHashesData
  627. if err := msg.Decode(&announces); err != nil {
  628. return errResp(ErrDecode, "%v: %v", msg, err)
  629. }
  630. // Mark the hashes as present at the remote node
  631. for _, block := range announces {
  632. p.MarkBlock(block.Hash)
  633. }
  634. // Schedule all the unknown hashes for retrieval
  635. unknown := make(newBlockHashesData, 0, len(announces))
  636. for _, block := range announces {
  637. if !pm.blockchain.HasBlock(block.Hash, block.Number) {
  638. unknown = append(unknown, block)
  639. }
  640. }
  641. for _, block := range unknown {
  642. pm.blockFetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestOneHeader, p.RequestBodies)
  643. }
  644. case msg.Code == NewBlockMsg:
  645. // Retrieve and decode the propagated block
  646. var request newBlockData
  647. if err := msg.Decode(&request); err != nil {
  648. return errResp(ErrDecode, "%v: %v", msg, err)
  649. }
  650. if hash := types.CalcUncleHash(request.Block.Uncles()); hash != request.Block.UncleHash() {
  651. log.Warn("Propagated block has invalid uncles", "have", hash, "exp", request.Block.UncleHash())
  652. break // TODO(karalabe): return error eventually, but wait a few releases
  653. }
  654. if hash := types.DeriveSha(request.Block.Transactions(), trie.NewStackTrie(nil)); hash != request.Block.TxHash() {
  655. log.Warn("Propagated block has invalid body", "have", hash, "exp", request.Block.TxHash())
  656. break // TODO(karalabe): return error eventually, but wait a few releases
  657. }
  658. if err := request.sanityCheck(); err != nil {
  659. return err
  660. }
  661. request.Block.ReceivedAt = msg.ReceivedAt
  662. request.Block.ReceivedFrom = p
  663. // Mark the peer as owning the block and schedule it for import
  664. p.MarkBlock(request.Block.Hash())
  665. pm.blockFetcher.Enqueue(p.id, request.Block)
  666. // Assuming the block is importable by the peer, but possibly not yet done so,
  667. // calculate the head hash and TD that the peer truly must have.
  668. var (
  669. trueHead = request.Block.ParentHash()
  670. trueTD = new(big.Int).Sub(request.TD, request.Block.Difficulty())
  671. )
  672. // Update the peer's total difficulty if better than the previous
  673. if _, td := p.Head(); trueTD.Cmp(td) > 0 {
  674. p.SetHead(trueHead, trueTD)
  675. pm.chainSync.handlePeerEvent(p)
  676. }
  677. case msg.Code == NewPooledTransactionHashesMsg && p.version >= eth65:
  678. // New transaction announcement arrived, make sure we have
  679. // a valid and fresh chain to handle them
  680. if atomic.LoadUint32(&pm.acceptTxs) == 0 {
  681. break
  682. }
  683. var hashes []common.Hash
  684. if err := msg.Decode(&hashes); err != nil {
  685. return errResp(ErrDecode, "msg %v: %v", msg, err)
  686. }
  687. // Schedule all the unknown hashes for retrieval
  688. for _, hash := range hashes {
  689. p.MarkTransaction(hash)
  690. }
  691. pm.txFetcher.Notify(p.id, hashes)
  692. case msg.Code == GetPooledTransactionsMsg && p.version >= eth65:
  693. // Decode the retrieval message
  694. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  695. if _, err := msgStream.List(); err != nil {
  696. return err
  697. }
  698. // Gather transactions until the fetch or network limits is reached
  699. var (
  700. hash common.Hash
  701. bytes int
  702. hashes []common.Hash
  703. txs []rlp.RawValue
  704. )
  705. for bytes < softResponseLimit {
  706. // Retrieve the hash of the next block
  707. if err := msgStream.Decode(&hash); err == rlp.EOL {
  708. break
  709. } else if err != nil {
  710. return errResp(ErrDecode, "msg %v: %v", msg, err)
  711. }
  712. // Retrieve the requested transaction, skipping if unknown to us
  713. tx := pm.txpool.Get(hash)
  714. if tx == nil {
  715. continue
  716. }
  717. // If known, encode and queue for response packet
  718. if encoded, err := rlp.EncodeToBytes(tx); err != nil {
  719. log.Error("Failed to encode transaction", "err", err)
  720. } else {
  721. hashes = append(hashes, hash)
  722. txs = append(txs, encoded)
  723. bytes += len(encoded)
  724. }
  725. }
  726. return p.SendPooledTransactionsRLP(hashes, txs)
  727. case msg.Code == TransactionMsg || (msg.Code == PooledTransactionsMsg && p.version >= eth65):
  728. // Transactions arrived, make sure we have a valid and fresh chain to handle them
  729. if atomic.LoadUint32(&pm.acceptTxs) == 0 {
  730. break
  731. }
  732. // Transactions can be processed, parse all of them and deliver to the pool
  733. var txs []*types.Transaction
  734. if err := msg.Decode(&txs); err != nil {
  735. return errResp(ErrDecode, "msg %v: %v", msg, err)
  736. }
  737. for i, tx := range txs {
  738. // Validate and mark the remote transaction
  739. if tx == nil {
  740. return errResp(ErrDecode, "transaction %d is nil", i)
  741. }
  742. p.MarkTransaction(tx.Hash())
  743. }
  744. pm.txFetcher.Enqueue(p.id, txs, msg.Code == PooledTransactionsMsg)
  745. default:
  746. return errResp(ErrInvalidMsgCode, "%v", msg.Code)
  747. }
  748. return nil
  749. }
  750. // BroadcastBlock will either propagate a block to a subset of its peers, or
  751. // will only announce its availability (depending what's requested).
  752. func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
  753. hash := block.Hash()
  754. peers := pm.peers.PeersWithoutBlock(hash)
  755. // If propagation is requested, send to a subset of the peer
  756. if propagate {
  757. // Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
  758. var td *big.Int
  759. if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
  760. td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1))
  761. } else {
  762. log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
  763. return
  764. }
  765. // Send the block to a subset of our peers
  766. transfer := peers[:int(math.Sqrt(float64(len(peers))))]
  767. for _, peer := range transfer {
  768. peer.AsyncSendNewBlock(block, td)
  769. }
  770. log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  771. return
  772. }
  773. // Otherwise if the block is indeed in out own chain, announce it
  774. if pm.blockchain.HasBlock(hash, block.NumberU64()) {
  775. for _, peer := range peers {
  776. peer.AsyncSendNewBlockHash(block)
  777. }
  778. log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  779. }
  780. }
  781. // BroadcastTransactions will propagate a batch of transactions to all peers which are not known to
  782. // already have the given transaction.
  783. func (pm *ProtocolManager) BroadcastTransactions(txs types.Transactions, propagate bool) {
  784. var (
  785. txset = make(map[*peer][]common.Hash)
  786. annos = make(map[*peer][]common.Hash)
  787. )
  788. // Broadcast transactions to a batch of peers not knowing about it
  789. if propagate {
  790. for _, tx := range txs {
  791. peers := pm.peers.PeersWithoutTx(tx.Hash())
  792. // Send the block to a subset of our peers
  793. transfer := peers[:int(math.Sqrt(float64(len(peers))))]
  794. for _, peer := range transfer {
  795. txset[peer] = append(txset[peer], tx.Hash())
  796. }
  797. log.Trace("Broadcast transaction", "hash", tx.Hash(), "recipients", len(peers))
  798. }
  799. for peer, hashes := range txset {
  800. peer.AsyncSendTransactions(hashes)
  801. }
  802. return
  803. }
  804. // Otherwise only broadcast the announcement to peers
  805. for _, tx := range txs {
  806. peers := pm.peers.PeersWithoutTx(tx.Hash())
  807. for _, peer := range peers {
  808. annos[peer] = append(annos[peer], tx.Hash())
  809. }
  810. }
  811. for peer, hashes := range annos {
  812. if peer.version >= eth65 {
  813. peer.AsyncSendPooledTransactionHashes(hashes)
  814. } else {
  815. peer.AsyncSendTransactions(hashes)
  816. }
  817. }
  818. }
  819. // minedBroadcastLoop sends mined blocks to connected peers.
  820. func (pm *ProtocolManager) minedBroadcastLoop() {
  821. defer pm.wg.Done()
  822. for obj := range pm.minedBlockSub.Chan() {
  823. if ev, ok := obj.Data.(core.NewMinedBlockEvent); ok {
  824. pm.BroadcastBlock(ev.Block, true) // First propagate block to peers
  825. pm.BroadcastBlock(ev.Block, false) // Only then announce to the rest
  826. }
  827. }
  828. }
  829. // txBroadcastLoop announces new transactions to connected peers.
  830. func (pm *ProtocolManager) txBroadcastLoop() {
  831. defer pm.wg.Done()
  832. for {
  833. select {
  834. case event := <-pm.txsCh:
  835. // For testing purpose only, disable propagation
  836. if pm.broadcastTxAnnouncesOnly {
  837. pm.BroadcastTransactions(event.Txs, false)
  838. continue
  839. }
  840. pm.BroadcastTransactions(event.Txs, true) // First propagate transactions to peers
  841. pm.BroadcastTransactions(event.Txs, false) // Only then announce to the rest
  842. case <-pm.txsSub.Err():
  843. return
  844. }
  845. }
  846. }
  847. // NodeInfo represents a short summary of the Ethereum sub-protocol metadata
  848. // known about the host peer.
  849. type NodeInfo struct {
  850. Network uint64 `json:"network"` // Ethereum network ID (1=Frontier, 2=Morden, Ropsten=3, Rinkeby=4)
  851. Difficulty *big.Int `json:"difficulty"` // Total difficulty of the host's blockchain
  852. Genesis common.Hash `json:"genesis"` // SHA3 hash of the host's genesis block
  853. Config *params.ChainConfig `json:"config"` // Chain configuration for the fork rules
  854. Head common.Hash `json:"head"` // SHA3 hash of the host's best owned block
  855. }
  856. // NodeInfo retrieves some protocol metadata about the running host node.
  857. func (pm *ProtocolManager) NodeInfo() *NodeInfo {
  858. currentBlock := pm.blockchain.CurrentBlock()
  859. return &NodeInfo{
  860. Network: pm.networkID,
  861. Difficulty: pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64()),
  862. Genesis: pm.blockchain.Genesis().Hash(),
  863. Config: pm.blockchain.Config(),
  864. Head: currentBlock.Hash(),
  865. }
  866. }