handler.go 26 KB

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