handler.go 28 KB

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