handler.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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/core"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/eth/downloader"
  30. "github.com/ethereum/go-ethereum/eth/fetcher"
  31. "github.com/ethereum/go-ethereum/ethdb"
  32. "github.com/ethereum/go-ethereum/event"
  33. "github.com/ethereum/go-ethereum/logger"
  34. "github.com/ethereum/go-ethereum/logger/glog"
  35. "github.com/ethereum/go-ethereum/p2p"
  36. "github.com/ethereum/go-ethereum/p2p/discover"
  37. "github.com/ethereum/go-ethereum/params"
  38. "github.com/ethereum/go-ethereum/pow"
  39. "github.com/ethereum/go-ethereum/rlp"
  40. )
  41. const (
  42. softResponseLimit = 2 * 1024 * 1024 // Target maximum size of returned blocks, headers or node data.
  43. estHeaderRlpSize = 500 // Approximate size of an RLP encoded block header
  44. )
  45. var (
  46. daoChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the DAO handshake challenge
  47. )
  48. // errIncompatibleConfig is returned if the requested protocols and configs are
  49. // not compatible (low protocol version restrictions and high requirements).
  50. var errIncompatibleConfig = errors.New("incompatible configuration")
  51. func errResp(code errCode, format string, v ...interface{}) error {
  52. return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...))
  53. }
  54. type ProtocolManager struct {
  55. networkId int
  56. fastSync uint32 // Flag whether fast sync is enabled (gets disabled if we already have blocks)
  57. synced uint32 // Flag whether we're considered synchronised (enables transaction processing)
  58. txpool txPool
  59. blockchain *core.BlockChain
  60. chaindb ethdb.Database
  61. chainconfig *params.ChainConfig
  62. maxPeers int
  63. downloader *downloader.Downloader
  64. fetcher *fetcher.Fetcher
  65. peers *peerSet
  66. SubProtocols []p2p.Protocol
  67. eventMux *event.TypeMux
  68. txSub *event.TypeMuxSubscription
  69. minedBlockSub *event.TypeMuxSubscription
  70. // channels for fetcher, syncer, txsyncLoop
  71. newPeerCh chan *peer
  72. txsyncCh chan *txsync
  73. quitSync chan struct{}
  74. noMorePeers chan struct{}
  75. lesServer LesServer
  76. // wait group is used for graceful shutdowns during downloading
  77. // and processing
  78. wg sync.WaitGroup
  79. badBlockReportingEnabled bool
  80. }
  81. // NewProtocolManager returns a new ethereum sub protocol manager. The Ethereum sub protocol manages peers capable
  82. // with the ethereum network.
  83. func NewProtocolManager(config *params.ChainConfig, fastSync bool, networkId int, maxPeers int, mux *event.TypeMux, txpool txPool, pow pow.PoW, blockchain *core.BlockChain, chaindb ethdb.Database) (*ProtocolManager, error) {
  84. // Create the protocol manager with the base fields
  85. manager := &ProtocolManager{
  86. networkId: networkId,
  87. eventMux: mux,
  88. txpool: txpool,
  89. blockchain: blockchain,
  90. chaindb: chaindb,
  91. chainconfig: config,
  92. maxPeers: maxPeers,
  93. peers: newPeerSet(),
  94. newPeerCh: make(chan *peer),
  95. noMorePeers: make(chan struct{}),
  96. txsyncCh: make(chan *txsync),
  97. quitSync: make(chan struct{}),
  98. }
  99. // Figure out whether to allow fast sync or not
  100. if fastSync && blockchain.CurrentBlock().NumberU64() > 0 {
  101. glog.V(logger.Info).Infof("blockchain not empty, fast sync disabled")
  102. fastSync = false
  103. }
  104. if fastSync {
  105. manager.fastSync = uint32(1)
  106. }
  107. // Initiate a sub-protocol for every implemented version we can handle
  108. manager.SubProtocols = make([]p2p.Protocol, 0, len(ProtocolVersions))
  109. for i, version := range ProtocolVersions {
  110. // Skip protocol version if incompatible with the mode of operation
  111. if fastSync && version < eth63 {
  112. continue
  113. }
  114. // Compatible; initialise the sub-protocol
  115. version := version // Closure for the run
  116. manager.SubProtocols = append(manager.SubProtocols, p2p.Protocol{
  117. Name: ProtocolName,
  118. Version: version,
  119. Length: ProtocolLengths[i],
  120. Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
  121. peer := manager.newPeer(int(version), p, rw)
  122. select {
  123. case manager.newPeerCh <- peer:
  124. manager.wg.Add(1)
  125. defer manager.wg.Done()
  126. return manager.handle(peer)
  127. case <-manager.quitSync:
  128. return p2p.DiscQuitting
  129. }
  130. },
  131. NodeInfo: func() interface{} {
  132. return manager.NodeInfo()
  133. },
  134. PeerInfo: func(id discover.NodeID) interface{} {
  135. if p := manager.peers.Peer(fmt.Sprintf("%x", id[:8])); p != nil {
  136. return p.Info()
  137. }
  138. return nil
  139. },
  140. })
  141. }
  142. if len(manager.SubProtocols) == 0 {
  143. return nil, errIncompatibleConfig
  144. }
  145. // Construct the different synchronisation mechanisms
  146. manager.downloader = downloader.New(downloader.FullSync, chaindb, manager.eventMux, blockchain.HasHeader, blockchain.HasBlockAndState, blockchain.GetHeaderByHash,
  147. blockchain.GetBlockByHash, blockchain.CurrentHeader, blockchain.CurrentBlock, blockchain.CurrentFastBlock, blockchain.FastSyncCommitHead,
  148. blockchain.GetTdByHash, blockchain.InsertHeaderChain, manager.insertChain, blockchain.InsertReceiptChain, blockchain.Rollback,
  149. manager.removePeer)
  150. validator := func(block *types.Block, parent *types.Block) error {
  151. return core.ValidateHeader(config, pow, block.Header(), parent.Header(), true, false)
  152. }
  153. heighter := func() uint64 {
  154. return blockchain.CurrentBlock().NumberU64()
  155. }
  156. inserter := func(blocks types.Blocks) (int, error) {
  157. atomic.StoreUint32(&manager.synced, 1) // Mark initial sync done on any fetcher import
  158. return manager.insertChain(blocks)
  159. }
  160. manager.fetcher = fetcher.New(blockchain.GetBlockByHash, validator, manager.BroadcastBlock, heighter, inserter, manager.removePeer)
  161. if blockchain.Genesis().Hash().Hex() == defaultGenesisHash && networkId == 1 {
  162. glog.V(logger.Debug).Infoln("Bad Block Reporting is enabled")
  163. manager.badBlockReportingEnabled = true
  164. }
  165. return manager, nil
  166. }
  167. func (pm *ProtocolManager) insertChain(blocks types.Blocks) (i int, err error) {
  168. i, err = pm.blockchain.InsertChain(blocks)
  169. if pm.badBlockReportingEnabled && core.IsValidationErr(err) && i < len(blocks) {
  170. go sendBadBlockReport(blocks[i], err)
  171. }
  172. return i, err
  173. }
  174. func (pm *ProtocolManager) removePeer(id string) {
  175. // Short circuit if the peer was already removed
  176. peer := pm.peers.Peer(id)
  177. if peer == nil {
  178. return
  179. }
  180. glog.V(logger.Debug).Infoln("Removing peer", id)
  181. // Unregister the peer from the downloader and Ethereum peer set
  182. pm.downloader.UnregisterPeer(id)
  183. if err := pm.peers.Unregister(id); err != nil {
  184. glog.V(logger.Error).Infoln("Removal failed:", err)
  185. }
  186. // Hard disconnect at the networking layer
  187. if peer != nil {
  188. peer.Peer.Disconnect(p2p.DiscUselessPeer)
  189. }
  190. }
  191. func (pm *ProtocolManager) Start() {
  192. // broadcast transactions
  193. pm.txSub = pm.eventMux.Subscribe(core.TxPreEvent{})
  194. go pm.txBroadcastLoop()
  195. // broadcast mined blocks
  196. pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
  197. go pm.minedBroadcastLoop()
  198. // start sync handlers
  199. go pm.syncer()
  200. go pm.txsyncLoop()
  201. }
  202. func (pm *ProtocolManager) Stop() {
  203. glog.V(logger.Info).Infoln("Stopping ethereum protocol handler...")
  204. pm.txSub.Unsubscribe() // quits txBroadcastLoop
  205. pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
  206. // Quit the sync loop.
  207. // After this send has completed, no new peers will be accepted.
  208. pm.noMorePeers <- struct{}{}
  209. // Quit fetcher, txsyncLoop.
  210. close(pm.quitSync)
  211. // Disconnect existing sessions.
  212. // This also closes the gate for any new registrations on the peer set.
  213. // sessions which are already established but not added to pm.peers yet
  214. // will exit when they try to register.
  215. pm.peers.Close()
  216. // Wait for all peer handler goroutines and the loops to come down.
  217. pm.wg.Wait()
  218. glog.V(logger.Info).Infoln("Ethereum protocol handler stopped")
  219. }
  220. func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
  221. return newPeer(pv, p, newMeteredMsgWriter(rw))
  222. }
  223. // handle is the callback invoked to manage the life cycle of an eth peer. When
  224. // this function terminates, the peer is disconnected.
  225. func (pm *ProtocolManager) handle(p *peer) error {
  226. if pm.peers.Len() >= pm.maxPeers {
  227. return p2p.DiscTooManyPeers
  228. }
  229. glog.V(logger.Debug).Infof("%v: peer connected [%s]", p, p.Name())
  230. // Execute the Ethereum handshake
  231. td, head, genesis := pm.blockchain.Status()
  232. if err := p.Handshake(pm.networkId, td, head, genesis); err != nil {
  233. glog.V(logger.Debug).Infof("%v: handshake failed: %v", p, err)
  234. return err
  235. }
  236. if rw, ok := p.rw.(*meteredMsgReadWriter); ok {
  237. rw.Init(p.version)
  238. }
  239. // Register the peer locally
  240. glog.V(logger.Detail).Infof("%v: adding peer", p)
  241. if err := pm.peers.Register(p); err != nil {
  242. glog.V(logger.Error).Infof("%v: addition failed: %v", p, err)
  243. return err
  244. }
  245. defer pm.removePeer(p.id)
  246. // Register the peer in the downloader. If the downloader considers it banned, we disconnect
  247. if err := pm.downloader.RegisterPeer(p.id, p.version, p.Head, p.RequestHeadersByHash, p.RequestHeadersByNumber, p.RequestBodies, p.RequestReceipts, p.RequestNodeData); err != nil {
  248. return err
  249. }
  250. // Propagate existing transactions. new transactions appearing
  251. // after this will be sent via broadcasts.
  252. pm.syncTransactions(p)
  253. // If we're DAO hard-fork aware, validate any remote peer with regard to the hard-fork
  254. if daoBlock := pm.chainconfig.DAOForkBlock; daoBlock != nil {
  255. // Request the peer's DAO fork header for extra-data validation
  256. if err := p.RequestHeadersByNumber(daoBlock.Uint64(), 1, 0, false); err != nil {
  257. return err
  258. }
  259. // Start a timer to disconnect if the peer doesn't reply in time
  260. p.forkDrop = time.AfterFunc(daoChallengeTimeout, func() {
  261. glog.V(logger.Debug).Infof("%v: timed out DAO fork-check, dropping", p)
  262. pm.removePeer(p.id)
  263. })
  264. // Make sure it's cleaned up if the peer dies off
  265. defer func() {
  266. if p.forkDrop != nil {
  267. p.forkDrop.Stop()
  268. p.forkDrop = nil
  269. }
  270. }()
  271. }
  272. // main loop. handle incoming messages.
  273. for {
  274. if err := pm.handleMsg(p); err != nil {
  275. glog.V(logger.Debug).Infof("%v: message handling failed: %v", p, err)
  276. return err
  277. }
  278. }
  279. }
  280. // handleMsg is invoked whenever an inbound message is received from a remote
  281. // peer. The remote connection is torn down upon returning any error.
  282. func (pm *ProtocolManager) handleMsg(p *peer) error {
  283. // Read the next message from the remote peer, and ensure it's fully consumed
  284. msg, err := p.rw.ReadMsg()
  285. if err != nil {
  286. return err
  287. }
  288. if msg.Size > ProtocolMaxMsgSize {
  289. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  290. }
  291. defer msg.Discard()
  292. // Handle the message depending on its contents
  293. switch {
  294. case msg.Code == StatusMsg:
  295. // Status messages should never arrive after the handshake
  296. return errResp(ErrExtraStatusMsg, "uncontrolled status message")
  297. // Block header query, collect the requested headers and reply
  298. case msg.Code == GetBlockHeadersMsg:
  299. // Decode the complex header query
  300. var query getBlockHeadersData
  301. if err := msg.Decode(&query); err != nil {
  302. return errResp(ErrDecode, "%v: %v", msg, err)
  303. }
  304. hashMode := query.Origin.Hash != (common.Hash{})
  305. // Gather headers until the fetch or network limits is reached
  306. var (
  307. bytes common.StorageSize
  308. headers []*types.Header
  309. unknown bool
  310. )
  311. for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch {
  312. // Retrieve the next header satisfying the query
  313. var origin *types.Header
  314. if hashMode {
  315. origin = pm.blockchain.GetHeaderByHash(query.Origin.Hash)
  316. } else {
  317. origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
  318. }
  319. if origin == nil {
  320. break
  321. }
  322. number := origin.Number.Uint64()
  323. headers = append(headers, origin)
  324. bytes += estHeaderRlpSize
  325. // Advance to the next header of the query
  326. switch {
  327. case query.Origin.Hash != (common.Hash{}) && query.Reverse:
  328. // Hash based traversal towards the genesis block
  329. for i := 0; i < int(query.Skip)+1; i++ {
  330. if header := pm.blockchain.GetHeader(query.Origin.Hash, number); header != nil {
  331. query.Origin.Hash = header.ParentHash
  332. number--
  333. } else {
  334. unknown = true
  335. break
  336. }
  337. }
  338. case query.Origin.Hash != (common.Hash{}) && !query.Reverse:
  339. // Hash based traversal towards the leaf block
  340. var (
  341. current = origin.Number.Uint64()
  342. next = current + query.Skip + 1
  343. )
  344. if next <= current {
  345. infos, _ := json.MarshalIndent(p.Peer.Info(), "", " ")
  346. glog.V(logger.Warn).Infof("%v: GetBlockHeaders skip overflow attack (current %v, skip %v, next %v)\nMalicious peer infos: %s", p, current, query.Skip, next, infos)
  347. unknown = true
  348. } else {
  349. if header := pm.blockchain.GetHeaderByNumber(next); header != nil {
  350. if pm.blockchain.GetBlockHashesFromHash(header.Hash(), query.Skip+1)[query.Skip] == query.Origin.Hash {
  351. query.Origin.Hash = header.Hash()
  352. } else {
  353. unknown = true
  354. }
  355. } else {
  356. unknown = true
  357. }
  358. }
  359. case query.Reverse:
  360. // Number based traversal towards the genesis block
  361. if query.Origin.Number >= query.Skip+1 {
  362. query.Origin.Number -= (query.Skip + 1)
  363. } else {
  364. unknown = true
  365. }
  366. case !query.Reverse:
  367. // Number based traversal towards the leaf block
  368. query.Origin.Number += (query.Skip + 1)
  369. }
  370. }
  371. return p.SendBlockHeaders(headers)
  372. case msg.Code == BlockHeadersMsg:
  373. // A batch of headers arrived to one of our previous requests
  374. var headers []*types.Header
  375. if err := msg.Decode(&headers); err != nil {
  376. return errResp(ErrDecode, "msg %v: %v", msg, err)
  377. }
  378. // If no headers were received, but we're expending a DAO fork check, maybe it's that
  379. if len(headers) == 0 && p.forkDrop != nil {
  380. // Possibly an empty reply to the fork header checks, sanity check TDs
  381. verifyDAO := true
  382. // If we already have a DAO header, we can check the peer's TD against it. If
  383. // the peer's ahead of this, it too must have a reply to the DAO check
  384. if daoHeader := pm.blockchain.GetHeaderByNumber(pm.chainconfig.DAOForkBlock.Uint64()); daoHeader != nil {
  385. if _, td := p.Head(); td.Cmp(pm.blockchain.GetTd(daoHeader.Hash(), daoHeader.Number.Uint64())) >= 0 {
  386. verifyDAO = false
  387. }
  388. }
  389. // If we're seemingly on the same chain, disable the drop timer
  390. if verifyDAO {
  391. glog.V(logger.Debug).Infof("%v: seems to be on the same side of the DAO fork", p)
  392. p.forkDrop.Stop()
  393. p.forkDrop = nil
  394. return nil
  395. }
  396. }
  397. // Filter out any explicitly requested headers, deliver the rest to the downloader
  398. filter := len(headers) == 1
  399. if filter {
  400. // If it's a potential DAO fork check, validate against the rules
  401. if p.forkDrop != nil && pm.chainconfig.DAOForkBlock.Cmp(headers[0].Number) == 0 {
  402. // Disable the fork drop timer
  403. p.forkDrop.Stop()
  404. p.forkDrop = nil
  405. // Validate the header and either drop the peer or continue
  406. if err := core.ValidateDAOHeaderExtraData(pm.chainconfig, headers[0]); err != nil {
  407. glog.V(logger.Debug).Infof("%v: verified to be on the other side of the DAO fork, dropping", p)
  408. return err
  409. }
  410. glog.V(logger.Debug).Infof("%v: verified to be on the same side of the DAO fork", p)
  411. return nil
  412. }
  413. // Irrelevant of the fork checks, send the header to the fetcher just in case
  414. headers = pm.fetcher.FilterHeaders(headers, time.Now())
  415. }
  416. if len(headers) > 0 || !filter {
  417. err := pm.downloader.DeliverHeaders(p.id, headers)
  418. if err != nil {
  419. glog.V(logger.Debug).Infoln(err)
  420. }
  421. }
  422. case msg.Code == GetBlockBodiesMsg:
  423. // Decode the retrieval message
  424. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  425. if _, err := msgStream.List(); err != nil {
  426. return err
  427. }
  428. // Gather blocks until the fetch or network limits is reached
  429. var (
  430. hash common.Hash
  431. bytes int
  432. bodies []rlp.RawValue
  433. )
  434. for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch {
  435. // Retrieve the hash of the next block
  436. if err := msgStream.Decode(&hash); err == rlp.EOL {
  437. break
  438. } else if err != nil {
  439. return errResp(ErrDecode, "msg %v: %v", msg, err)
  440. }
  441. // Retrieve the requested block body, stopping if enough was found
  442. if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 {
  443. bodies = append(bodies, data)
  444. bytes += len(data)
  445. }
  446. }
  447. return p.SendBlockBodiesRLP(bodies)
  448. case msg.Code == BlockBodiesMsg:
  449. // A batch of block bodies arrived to one of our previous requests
  450. var request blockBodiesData
  451. if err := msg.Decode(&request); err != nil {
  452. return errResp(ErrDecode, "msg %v: %v", msg, err)
  453. }
  454. // Deliver them all to the downloader for queuing
  455. trasactions := make([][]*types.Transaction, len(request))
  456. uncles := make([][]*types.Header, len(request))
  457. for i, body := range request {
  458. trasactions[i] = body.Transactions
  459. uncles[i] = body.Uncles
  460. }
  461. // Filter out any explicitly requested bodies, deliver the rest to the downloader
  462. filter := len(trasactions) > 0 || len(uncles) > 0
  463. if filter {
  464. trasactions, uncles = pm.fetcher.FilterBodies(trasactions, uncles, time.Now())
  465. }
  466. if len(trasactions) > 0 || len(uncles) > 0 || !filter {
  467. err := pm.downloader.DeliverBodies(p.id, trasactions, uncles)
  468. if err != nil {
  469. glog.V(logger.Debug).Infoln(err)
  470. }
  471. }
  472. case p.version >= eth63 && msg.Code == GetNodeDataMsg:
  473. // Decode the retrieval message
  474. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  475. if _, err := msgStream.List(); err != nil {
  476. return err
  477. }
  478. // Gather state data until the fetch or network limits is reached
  479. var (
  480. hash common.Hash
  481. bytes int
  482. data [][]byte
  483. )
  484. for bytes < softResponseLimit && len(data) < downloader.MaxStateFetch {
  485. // Retrieve the hash of the next state entry
  486. if err := msgStream.Decode(&hash); err == rlp.EOL {
  487. break
  488. } else if err != nil {
  489. return errResp(ErrDecode, "msg %v: %v", msg, err)
  490. }
  491. // Retrieve the requested state entry, stopping if enough was found
  492. if entry, err := pm.chaindb.Get(hash.Bytes()); err == nil {
  493. data = append(data, entry)
  494. bytes += len(entry)
  495. }
  496. }
  497. return p.SendNodeData(data)
  498. case p.version >= eth63 && msg.Code == NodeDataMsg:
  499. // A batch of node state data arrived to one of our previous requests
  500. var data [][]byte
  501. if err := msg.Decode(&data); err != nil {
  502. return errResp(ErrDecode, "msg %v: %v", msg, err)
  503. }
  504. // Deliver all to the downloader
  505. if err := pm.downloader.DeliverNodeData(p.id, data); err != nil {
  506. glog.V(logger.Debug).Infof("failed to deliver node state data: %v", err)
  507. }
  508. case p.version >= eth63 && msg.Code == GetReceiptsMsg:
  509. // Decode the retrieval message
  510. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  511. if _, err := msgStream.List(); err != nil {
  512. return err
  513. }
  514. // Gather state data until the fetch or network limits is reached
  515. var (
  516. hash common.Hash
  517. bytes int
  518. receipts []rlp.RawValue
  519. )
  520. for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch {
  521. // Retrieve the hash of the next block
  522. if err := msgStream.Decode(&hash); err == rlp.EOL {
  523. break
  524. } else if err != nil {
  525. return errResp(ErrDecode, "msg %v: %v", msg, err)
  526. }
  527. // Retrieve the requested block's receipts, skipping if unknown to us
  528. results := core.GetBlockReceipts(pm.chaindb, hash, core.GetBlockNumber(pm.chaindb, hash))
  529. if results == nil {
  530. if header := pm.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
  531. continue
  532. }
  533. }
  534. // If known, encode and queue for response packet
  535. if encoded, err := rlp.EncodeToBytes(results); err != nil {
  536. glog.V(logger.Error).Infof("failed to encode receipt: %v", err)
  537. } else {
  538. receipts = append(receipts, encoded)
  539. bytes += len(encoded)
  540. }
  541. }
  542. return p.SendReceiptsRLP(receipts)
  543. case p.version >= eth63 && msg.Code == ReceiptsMsg:
  544. // A batch of receipts arrived to one of our previous requests
  545. var receipts [][]*types.Receipt
  546. if err := msg.Decode(&receipts); err != nil {
  547. return errResp(ErrDecode, "msg %v: %v", msg, err)
  548. }
  549. // Deliver all to the downloader
  550. if err := pm.downloader.DeliverReceipts(p.id, receipts); err != nil {
  551. glog.V(logger.Debug).Infof("failed to deliver receipts: %v", err)
  552. }
  553. case msg.Code == NewBlockHashesMsg:
  554. var announces newBlockHashesData
  555. if err := msg.Decode(&announces); err != nil {
  556. return errResp(ErrDecode, "%v: %v", msg, err)
  557. }
  558. // Mark the hashes as present at the remote node
  559. for _, block := range announces {
  560. p.MarkBlock(block.Hash)
  561. }
  562. // Schedule all the unknown hashes for retrieval
  563. unknown := make(newBlockHashesData, 0, len(announces))
  564. for _, block := range announces {
  565. if !pm.blockchain.HasBlock(block.Hash) {
  566. unknown = append(unknown, block)
  567. }
  568. }
  569. for _, block := range unknown {
  570. pm.fetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestOneHeader, p.RequestBodies)
  571. }
  572. case msg.Code == NewBlockMsg:
  573. // Retrieve and decode the propagated block
  574. var request newBlockData
  575. if err := msg.Decode(&request); err != nil {
  576. return errResp(ErrDecode, "%v: %v", msg, err)
  577. }
  578. request.Block.ReceivedAt = msg.ReceivedAt
  579. request.Block.ReceivedFrom = p
  580. // Mark the peer as owning the block and schedule it for import
  581. p.MarkBlock(request.Block.Hash())
  582. pm.fetcher.Enqueue(p.id, request.Block)
  583. // Assuming the block is importable by the peer, but possibly not yet done so,
  584. // calculate the head hash and TD that the peer truly must have.
  585. var (
  586. trueHead = request.Block.ParentHash()
  587. trueTD = new(big.Int).Sub(request.TD, request.Block.Difficulty())
  588. )
  589. // Update the peers total difficulty if better than the previous
  590. if _, td := p.Head(); trueTD.Cmp(td) > 0 {
  591. p.SetHead(trueHead, trueTD)
  592. // Schedule a sync if above ours. Note, this will not fire a sync for a gap of
  593. // a singe block (as the true TD is below the propagated block), however this
  594. // scenario should easily be covered by the fetcher.
  595. currentBlock := pm.blockchain.CurrentBlock()
  596. if trueTD.Cmp(pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64())) > 0 {
  597. go pm.synchronise(p)
  598. }
  599. }
  600. case msg.Code == TxMsg:
  601. // Transactions arrived, make sure we have a valid and fresh chain to handle them
  602. if atomic.LoadUint32(&pm.synced) == 0 {
  603. break
  604. }
  605. // Transactions can be processed, parse all of them and deliver to the pool
  606. var txs []*types.Transaction
  607. if err := msg.Decode(&txs); err != nil {
  608. return errResp(ErrDecode, "msg %v: %v", msg, err)
  609. }
  610. for i, tx := range txs {
  611. // Validate and mark the remote transaction
  612. if tx == nil {
  613. return errResp(ErrDecode, "transaction %d is nil", i)
  614. }
  615. p.MarkTransaction(tx.Hash())
  616. }
  617. pm.txpool.AddBatch(txs)
  618. default:
  619. return errResp(ErrInvalidMsgCode, "%v", msg.Code)
  620. }
  621. return nil
  622. }
  623. // BroadcastBlock will either propagate a block to a subset of it's peers, or
  624. // will only announce it's availability (depending what's requested).
  625. func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
  626. hash := block.Hash()
  627. peers := pm.peers.PeersWithoutBlock(hash)
  628. // If propagation is requested, send to a subset of the peer
  629. if propagate {
  630. // Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
  631. var td *big.Int
  632. if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
  633. td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1))
  634. } else {
  635. glog.V(logger.Error).Infof("propagating dangling block #%d [%x]", block.NumberU64(), hash[:4])
  636. return
  637. }
  638. // Send the block to a subset of our peers
  639. transfer := peers[:int(math.Sqrt(float64(len(peers))))]
  640. for _, peer := range transfer {
  641. peer.SendNewBlock(block, td)
  642. }
  643. glog.V(logger.Detail).Infof("propagated block %x to %d peers in %v", hash[:4], len(transfer), time.Since(block.ReceivedAt))
  644. }
  645. // Otherwise if the block is indeed in out own chain, announce it
  646. if pm.blockchain.HasBlock(hash) {
  647. for _, peer := range peers {
  648. peer.SendNewBlockHashes([]common.Hash{hash}, []uint64{block.NumberU64()})
  649. }
  650. glog.V(logger.Detail).Infof("announced block %x to %d peers in %v", hash[:4], len(peers), time.Since(block.ReceivedAt))
  651. }
  652. }
  653. // BroadcastTx will propagate a transaction to all peers which are not known to
  654. // already have the given transaction.
  655. func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *types.Transaction) {
  656. // Broadcast transaction to a batch of peers not knowing about it
  657. peers := pm.peers.PeersWithoutTx(hash)
  658. //FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))]
  659. for _, peer := range peers {
  660. peer.SendTransactions(types.Transactions{tx})
  661. }
  662. glog.V(logger.Detail).Infoln("broadcast tx to", len(peers), "peers")
  663. }
  664. // Mined broadcast loop
  665. func (self *ProtocolManager) minedBroadcastLoop() {
  666. // automatically stops if unsubscribe
  667. for obj := range self.minedBlockSub.Chan() {
  668. switch ev := obj.Data.(type) {
  669. case core.NewMinedBlockEvent:
  670. self.BroadcastBlock(ev.Block, true) // First propagate block to peers
  671. self.BroadcastBlock(ev.Block, false) // Only then announce to the rest
  672. }
  673. }
  674. }
  675. func (self *ProtocolManager) txBroadcastLoop() {
  676. // automatically stops if unsubscribe
  677. for obj := range self.txSub.Chan() {
  678. event := obj.Data.(core.TxPreEvent)
  679. self.BroadcastTx(event.Tx.Hash(), event.Tx)
  680. }
  681. }
  682. // EthNodeInfo represents a short summary of the Ethereum sub-protocol metadata known
  683. // about the host peer.
  684. type EthNodeInfo struct {
  685. Network int `json:"network"` // Ethereum network ID (1=Frontier, 2=Morden, Ropsten=3)
  686. Difficulty *big.Int `json:"difficulty"` // Total difficulty of the host's blockchain
  687. Genesis common.Hash `json:"genesis"` // SHA3 hash of the host's genesis block
  688. Head common.Hash `json:"head"` // SHA3 hash of the host's best owned block
  689. }
  690. // NodeInfo retrieves some protocol metadata about the running host node.
  691. func (self *ProtocolManager) NodeInfo() *EthNodeInfo {
  692. currentBlock := self.blockchain.CurrentBlock()
  693. return &EthNodeInfo{
  694. Network: self.networkId,
  695. Difficulty: self.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64()),
  696. Genesis: self.blockchain.Genesis().Hash(),
  697. Head: currentBlock.Hash(),
  698. }
  699. }