handler.go 27 KB

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