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. "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. // wait group is used for graceful shutdowns during downloading
  68. // and processing
  69. wg sync.WaitGroup
  70. quit bool
  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, 1),
  90. txsyncCh: make(chan *txsync),
  91. quitSync: make(chan struct{}),
  92. }
  93. // Initiate a sub-protocol for every implemented version we can handle
  94. manager.SubProtocols = make([]p2p.Protocol, 0, len(ProtocolVersions))
  95. for i, version := range ProtocolVersions {
  96. // Skip protocol version if incompatible with the mode of operation
  97. if fastSync && version < eth63 {
  98. continue
  99. }
  100. // Compatible; initialise the sub-protocol
  101. version := version // Closure for the run
  102. manager.SubProtocols = append(manager.SubProtocols, p2p.Protocol{
  103. Name: ProtocolName,
  104. Version: version,
  105. Length: ProtocolLengths[i],
  106. Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
  107. peer := manager.newPeer(int(version), p, rw)
  108. manager.newPeerCh <- peer
  109. return manager.handle(peer)
  110. },
  111. NodeInfo: func() interface{} {
  112. return manager.NodeInfo()
  113. },
  114. PeerInfo: func(id discover.NodeID) interface{} {
  115. if p := manager.peers.Peer(fmt.Sprintf("%x", id[:8])); p != nil {
  116. return p.Info()
  117. }
  118. return nil
  119. },
  120. })
  121. }
  122. if len(manager.SubProtocols) == 0 {
  123. return nil, errIncompatibleConfig
  124. }
  125. // Construct the different synchronisation mechanisms
  126. manager.downloader = downloader.New(chaindb, manager.eventMux, blockchain.HasHeader, blockchain.HasBlockAndState, blockchain.GetHeader,
  127. blockchain.GetBlock, blockchain.CurrentHeader, blockchain.CurrentBlock, blockchain.CurrentFastBlock, blockchain.FastSyncCommitHead,
  128. blockchain.GetTd, blockchain.InsertHeaderChain, blockchain.InsertChain, blockchain.InsertReceiptChain, blockchain.Rollback,
  129. manager.removePeer)
  130. validator := func(block *types.Block, parent *types.Block) error {
  131. return core.ValidateHeader(config, pow, block.Header(), parent.Header(), true, false)
  132. }
  133. heighter := func() uint64 {
  134. return blockchain.CurrentBlock().NumberU64()
  135. }
  136. manager.fetcher = fetcher.New(blockchain.GetBlock, validator, manager.BroadcastBlock, heighter, blockchain.InsertChain, manager.removePeer)
  137. return manager, nil
  138. }
  139. func (pm *ProtocolManager) removePeer(id string) {
  140. // Short circuit if the peer was already removed
  141. peer := pm.peers.Peer(id)
  142. if peer == nil {
  143. return
  144. }
  145. glog.V(logger.Debug).Infoln("Removing peer", id)
  146. // Unregister the peer from the downloader and Ethereum peer set
  147. pm.downloader.UnregisterPeer(id)
  148. if err := pm.peers.Unregister(id); err != nil {
  149. glog.V(logger.Error).Infoln("Removal failed:", err)
  150. }
  151. // Hard disconnect at the networking layer
  152. if peer != nil {
  153. peer.Peer.Disconnect(p2p.DiscUselessPeer)
  154. }
  155. }
  156. func (pm *ProtocolManager) Start() {
  157. // broadcast transactions
  158. pm.txSub = pm.eventMux.Subscribe(core.TxPreEvent{})
  159. go pm.txBroadcastLoop()
  160. // broadcast mined blocks
  161. pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
  162. go pm.minedBroadcastLoop()
  163. // start sync handlers
  164. go pm.syncer()
  165. go pm.txsyncLoop()
  166. }
  167. func (pm *ProtocolManager) Stop() {
  168. // Showing a log message. During download / process this could actually
  169. // take between 5 to 10 seconds and therefor feedback is required.
  170. glog.V(logger.Info).Infoln("Stopping ethereum protocol handler...")
  171. pm.quit = true
  172. pm.txSub.Unsubscribe() // quits txBroadcastLoop
  173. pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
  174. close(pm.quitSync) // quits syncer, fetcher, txsyncLoop
  175. // Wait for any process action
  176. pm.wg.Wait()
  177. glog.V(logger.Info).Infoln("Ethereum protocol handler stopped")
  178. }
  179. func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
  180. return newPeer(pv, p, newMeteredMsgWriter(rw))
  181. }
  182. // handle is the callback invoked to manage the life cycle of an eth peer. When
  183. // this function terminates, the peer is disconnected.
  184. func (pm *ProtocolManager) handle(p *peer) error {
  185. glog.V(logger.Debug).Infof("%v: peer connected [%s]", p, p.Name())
  186. // Execute the Ethereum handshake
  187. td, head, genesis := pm.blockchain.Status()
  188. if err := p.Handshake(pm.networkId, td, head, genesis); err != nil {
  189. glog.V(logger.Debug).Infof("%v: handshake failed: %v", p, err)
  190. return err
  191. }
  192. if rw, ok := p.rw.(*meteredMsgReadWriter); ok {
  193. rw.Init(p.version)
  194. }
  195. // Register the peer locally
  196. glog.V(logger.Detail).Infof("%v: adding peer", p)
  197. if err := pm.peers.Register(p); err != nil {
  198. glog.V(logger.Error).Infof("%v: addition failed: %v", p, err)
  199. return err
  200. }
  201. defer pm.removePeer(p.id)
  202. // Register the peer in the downloader. If the downloader considers it banned, we disconnect
  203. if err := pm.downloader.RegisterPeer(p.id, p.version, p.Head(),
  204. p.RequestHashes, p.RequestHashesFromNumber, p.RequestBlocks, p.RequestHeadersByHash,
  205. p.RequestHeadersByNumber, p.RequestBodies, p.RequestReceipts, p.RequestNodeData); err != nil {
  206. return err
  207. }
  208. // Propagate existing transactions. new transactions appearing
  209. // after this will be sent via broadcasts.
  210. pm.syncTransactions(p)
  211. // main loop. handle incoming messages.
  212. for {
  213. if err := pm.handleMsg(p); err != nil {
  214. glog.V(logger.Debug).Infof("%v: message handling failed: %v", p, err)
  215. return err
  216. }
  217. }
  218. }
  219. // handleMsg is invoked whenever an inbound message is received from a remote
  220. // peer. The remote connection is torn down upon returning any error.
  221. func (pm *ProtocolManager) handleMsg(p *peer) error {
  222. // Read the next message from the remote peer, and ensure it's fully consumed
  223. msg, err := p.rw.ReadMsg()
  224. if err != nil {
  225. return err
  226. }
  227. if msg.Size > ProtocolMaxMsgSize {
  228. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  229. }
  230. defer msg.Discard()
  231. // Handle the message depending on its contents
  232. switch {
  233. case msg.Code == StatusMsg:
  234. // Status messages should never arrive after the handshake
  235. return errResp(ErrExtraStatusMsg, "uncontrolled status message")
  236. case p.version < eth62 && msg.Code == GetBlockHashesMsg:
  237. // Retrieve the number of hashes to return and from which origin hash
  238. var request getBlockHashesData
  239. if err := msg.Decode(&request); err != nil {
  240. return errResp(ErrDecode, "%v: %v", msg, err)
  241. }
  242. if request.Amount > uint64(downloader.MaxHashFetch) {
  243. request.Amount = uint64(downloader.MaxHashFetch)
  244. }
  245. // Retrieve the hashes from the block chain and return them
  246. hashes := pm.blockchain.GetBlockHashesFromHash(request.Hash, request.Amount)
  247. if len(hashes) == 0 {
  248. glog.V(logger.Debug).Infof("invalid block hash %x", request.Hash.Bytes()[:4])
  249. }
  250. return p.SendBlockHashes(hashes)
  251. case p.version < eth62 && msg.Code == GetBlockHashesFromNumberMsg:
  252. // Retrieve and decode the number of hashes to return and from which origin number
  253. var request getBlockHashesFromNumberData
  254. if err := msg.Decode(&request); err != nil {
  255. return errResp(ErrDecode, "%v: %v", msg, err)
  256. }
  257. if request.Amount > uint64(downloader.MaxHashFetch) {
  258. request.Amount = uint64(downloader.MaxHashFetch)
  259. }
  260. // Calculate the last block that should be retrieved, and short circuit if unavailable
  261. last := pm.blockchain.GetBlockByNumber(request.Number + request.Amount - 1)
  262. if last == nil {
  263. last = pm.blockchain.CurrentBlock()
  264. request.Amount = last.NumberU64() - request.Number + 1
  265. }
  266. if last.NumberU64() < request.Number {
  267. return p.SendBlockHashes(nil)
  268. }
  269. // Retrieve the hashes from the last block backwards, reverse and return
  270. hashes := []common.Hash{last.Hash()}
  271. hashes = append(hashes, pm.blockchain.GetBlockHashesFromHash(last.Hash(), request.Amount-1)...)
  272. for i := 0; i < len(hashes)/2; i++ {
  273. hashes[i], hashes[len(hashes)-1-i] = hashes[len(hashes)-1-i], hashes[i]
  274. }
  275. return p.SendBlockHashes(hashes)
  276. case p.version < eth62 && msg.Code == BlockHashesMsg:
  277. // A batch of hashes arrived to one of our previous requests
  278. var hashes []common.Hash
  279. if err := msg.Decode(&hashes); err != nil {
  280. break
  281. }
  282. // Deliver them all to the downloader for queuing
  283. err := pm.downloader.DeliverHashes(p.id, hashes)
  284. if err != nil {
  285. glog.V(logger.Debug).Infoln(err)
  286. }
  287. case p.version < eth62 && msg.Code == GetBlocksMsg:
  288. // Decode the retrieval message
  289. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  290. if _, err := msgStream.List(); err != nil {
  291. return err
  292. }
  293. // Gather blocks until the fetch or network limits is reached
  294. var (
  295. hash common.Hash
  296. bytes common.StorageSize
  297. blocks []*types.Block
  298. )
  299. for len(blocks) < downloader.MaxBlockFetch && bytes < softResponseLimit {
  300. //Retrieve the hash of the next block
  301. err := msgStream.Decode(&hash)
  302. if err == rlp.EOL {
  303. break
  304. } else if err != nil {
  305. return errResp(ErrDecode, "msg %v: %v", msg, err)
  306. }
  307. // Retrieve the requested block, stopping if enough was found
  308. if block := pm.blockchain.GetBlock(hash); block != nil {
  309. blocks = append(blocks, block)
  310. bytes += block.Size()
  311. }
  312. }
  313. return p.SendBlocks(blocks)
  314. case p.version < eth62 && msg.Code == BlocksMsg:
  315. // Decode the arrived block message
  316. var blocks []*types.Block
  317. if err := msg.Decode(&blocks); err != nil {
  318. glog.V(logger.Detail).Infoln("Decode error", err)
  319. blocks = nil
  320. }
  321. // Update the receive timestamp of each block
  322. for _, block := range blocks {
  323. block.ReceivedAt = msg.ReceivedAt
  324. }
  325. // Filter out any explicitly requested blocks, deliver the rest to the downloader
  326. if blocks := pm.fetcher.FilterBlocks(blocks); len(blocks) > 0 {
  327. pm.downloader.DeliverBlocks(p.id, blocks)
  328. }
  329. // Block header query, collect the requested headers and reply
  330. case p.version >= eth62 && msg.Code == GetBlockHeadersMsg:
  331. // Decode the complex header query
  332. var query getBlockHeadersData
  333. if err := msg.Decode(&query); err != nil {
  334. return errResp(ErrDecode, "%v: %v", msg, err)
  335. }
  336. hashMode := query.Origin.Hash != (common.Hash{})
  337. // Gather headers until the fetch or network limits is reached
  338. var (
  339. bytes common.StorageSize
  340. headers []*types.Header
  341. unknown bool
  342. )
  343. for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch {
  344. // Retrieve the next header satisfying the query
  345. var origin *types.Header
  346. if hashMode {
  347. origin = pm.blockchain.GetHeader(query.Origin.Hash)
  348. } else {
  349. origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
  350. }
  351. if origin == nil {
  352. break
  353. }
  354. headers = append(headers, origin)
  355. bytes += estHeaderRlpSize
  356. // Advance to the next header of the query
  357. switch {
  358. case query.Origin.Hash != (common.Hash{}) && query.Reverse:
  359. // Hash based traversal towards the genesis block
  360. for i := 0; i < int(query.Skip)+1; i++ {
  361. if header := pm.blockchain.GetHeader(query.Origin.Hash); header != nil {
  362. query.Origin.Hash = header.ParentHash
  363. } else {
  364. unknown = true
  365. break
  366. }
  367. }
  368. case query.Origin.Hash != (common.Hash{}) && !query.Reverse:
  369. // Hash based traversal towards the leaf block
  370. if header := pm.blockchain.GetHeaderByNumber(origin.Number.Uint64() + query.Skip + 1); header != nil {
  371. if pm.blockchain.GetBlockHashesFromHash(header.Hash(), query.Skip+1)[query.Skip] == query.Origin.Hash {
  372. query.Origin.Hash = header.Hash()
  373. } else {
  374. unknown = true
  375. }
  376. } else {
  377. unknown = true
  378. }
  379. case query.Reverse:
  380. // Number based traversal towards the genesis block
  381. if query.Origin.Number >= query.Skip+1 {
  382. query.Origin.Number -= (query.Skip + 1)
  383. } else {
  384. unknown = true
  385. }
  386. case !query.Reverse:
  387. // Number based traversal towards the leaf block
  388. query.Origin.Number += (query.Skip + 1)
  389. }
  390. }
  391. return p.SendBlockHeaders(headers)
  392. case p.version >= eth62 && msg.Code == BlockHeadersMsg:
  393. // A batch of headers arrived to one of our previous requests
  394. var headers []*types.Header
  395. if err := msg.Decode(&headers); err != nil {
  396. return errResp(ErrDecode, "msg %v: %v", msg, err)
  397. }
  398. // Filter out any explicitly requested headers, deliver the rest to the downloader
  399. filter := len(headers) == 1
  400. if filter {
  401. headers = pm.fetcher.FilterHeaders(headers, time.Now())
  402. }
  403. if len(headers) > 0 || !filter {
  404. err := pm.downloader.DeliverHeaders(p.id, headers)
  405. if err != nil {
  406. glog.V(logger.Debug).Infoln(err)
  407. }
  408. }
  409. case p.version >= eth62 && msg.Code == GetBlockBodiesMsg:
  410. // Decode the retrieval message
  411. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  412. if _, err := msgStream.List(); err != nil {
  413. return err
  414. }
  415. // Gather blocks until the fetch or network limits is reached
  416. var (
  417. hash common.Hash
  418. bytes int
  419. bodies []rlp.RawValue
  420. )
  421. for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch {
  422. // Retrieve the hash of the next block
  423. if err := msgStream.Decode(&hash); err == rlp.EOL {
  424. break
  425. } else if err != nil {
  426. return errResp(ErrDecode, "msg %v: %v", msg, err)
  427. }
  428. // Retrieve the requested block body, stopping if enough was found
  429. if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 {
  430. bodies = append(bodies, data)
  431. bytes += len(data)
  432. }
  433. }
  434. return p.SendBlockBodiesRLP(bodies)
  435. case p.version >= eth62 && msg.Code == BlockBodiesMsg:
  436. // A batch of block bodies arrived to one of our previous requests
  437. var request blockBodiesData
  438. if err := msg.Decode(&request); err != nil {
  439. return errResp(ErrDecode, "msg %v: %v", msg, err)
  440. }
  441. // Deliver them all to the downloader for queuing
  442. trasactions := make([][]*types.Transaction, len(request))
  443. uncles := make([][]*types.Header, len(request))
  444. for i, body := range request {
  445. trasactions[i] = body.Transactions
  446. uncles[i] = body.Uncles
  447. }
  448. // Filter out any explicitly requested bodies, deliver the rest to the downloader
  449. filter := len(trasactions) > 0 || len(uncles) > 0
  450. if filter {
  451. trasactions, uncles = pm.fetcher.FilterBodies(trasactions, uncles, time.Now())
  452. }
  453. if len(trasactions) > 0 || len(uncles) > 0 || !filter {
  454. err := pm.downloader.DeliverBodies(p.id, trasactions, uncles)
  455. if err != nil {
  456. glog.V(logger.Debug).Infoln(err)
  457. }
  458. }
  459. case p.version >= eth63 && msg.Code == GetNodeDataMsg:
  460. // Decode the retrieval message
  461. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  462. if _, err := msgStream.List(); err != nil {
  463. return err
  464. }
  465. // Gather state data until the fetch or network limits is reached
  466. var (
  467. hash common.Hash
  468. bytes int
  469. data [][]byte
  470. )
  471. for bytes < softResponseLimit && len(data) < downloader.MaxStateFetch {
  472. // Retrieve the hash of the next state entry
  473. if err := msgStream.Decode(&hash); err == rlp.EOL {
  474. break
  475. } else if err != nil {
  476. return errResp(ErrDecode, "msg %v: %v", msg, err)
  477. }
  478. // Retrieve the requested state entry, stopping if enough was found
  479. if entry, err := pm.chaindb.Get(hash.Bytes()); err == nil {
  480. data = append(data, entry)
  481. bytes += len(entry)
  482. }
  483. }
  484. return p.SendNodeData(data)
  485. case p.version >= eth63 && msg.Code == NodeDataMsg:
  486. // A batch of node state data arrived to one of our previous requests
  487. var data [][]byte
  488. if err := msg.Decode(&data); err != nil {
  489. return errResp(ErrDecode, "msg %v: %v", msg, err)
  490. }
  491. // Deliver all to the downloader
  492. if err := pm.downloader.DeliverNodeData(p.id, data); err != nil {
  493. glog.V(logger.Debug).Infof("failed to deliver node state data: %v", err)
  494. }
  495. case p.version >= eth63 && msg.Code == GetReceiptsMsg:
  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. receipts []rlp.RawValue
  506. )
  507. for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch {
  508. // Retrieve the hash of the next block
  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 block's receipts, skipping if unknown to us
  515. results := core.GetBlockReceipts(pm.chaindb, hash)
  516. if results == nil {
  517. if header := pm.blockchain.GetHeader(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
  518. continue
  519. }
  520. }
  521. // If known, encode and queue for response packet
  522. if encoded, err := rlp.EncodeToBytes(results); err != nil {
  523. glog.V(logger.Error).Infof("failed to encode receipt: %v", err)
  524. } else {
  525. receipts = append(receipts, encoded)
  526. bytes += len(encoded)
  527. }
  528. }
  529. return p.SendReceiptsRLP(receipts)
  530. case p.version >= eth63 && msg.Code == ReceiptsMsg:
  531. // A batch of receipts arrived to one of our previous requests
  532. var receipts [][]*types.Receipt
  533. if err := msg.Decode(&receipts); err != nil {
  534. return errResp(ErrDecode, "msg %v: %v", msg, err)
  535. }
  536. // Deliver all to the downloader
  537. if err := pm.downloader.DeliverReceipts(p.id, receipts); err != nil {
  538. glog.V(logger.Debug).Infof("failed to deliver receipts: %v", err)
  539. }
  540. case msg.Code == NewBlockHashesMsg:
  541. // Retrieve and deserialize the remote new block hashes notification
  542. type announce struct {
  543. Hash common.Hash
  544. Number uint64
  545. }
  546. var announces = []announce{}
  547. if p.version < eth62 {
  548. // We're running the old protocol, make block number unknown (0)
  549. var hashes []common.Hash
  550. if err := msg.Decode(&hashes); err != nil {
  551. return errResp(ErrDecode, "%v: %v", msg, err)
  552. }
  553. for _, hash := range hashes {
  554. announces = append(announces, announce{hash, 0})
  555. }
  556. } else {
  557. // Otherwise extract both block hash and number
  558. var request newBlockHashesData
  559. if err := msg.Decode(&request); err != nil {
  560. return errResp(ErrDecode, "%v: %v", msg, err)
  561. }
  562. for _, block := range request {
  563. announces = append(announces, announce{block.Hash, block.Number})
  564. }
  565. }
  566. // Mark the hashes as present at the remote node
  567. for _, block := range announces {
  568. p.MarkBlock(block.Hash)
  569. p.SetHead(block.Hash)
  570. }
  571. // Schedule all the unknown hashes for retrieval
  572. unknown := make([]announce, 0, len(announces))
  573. for _, block := range announces {
  574. if !pm.blockchain.HasBlock(block.Hash) {
  575. unknown = append(unknown, block)
  576. }
  577. }
  578. for _, block := range unknown {
  579. if p.version < eth62 {
  580. pm.fetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestBlocks, nil, nil)
  581. } else {
  582. pm.fetcher.Notify(p.id, block.Hash, block.Number, time.Now(), nil, p.RequestOneHeader, p.RequestBodies)
  583. }
  584. }
  585. case msg.Code == NewBlockMsg:
  586. // Retrieve and decode the propagated block
  587. var request newBlockData
  588. if err := msg.Decode(&request); err != nil {
  589. return errResp(ErrDecode, "%v: %v", msg, err)
  590. }
  591. if err := request.Block.ValidateFields(); err != nil {
  592. return errResp(ErrDecode, "block validation %v: %v", msg, err)
  593. }
  594. request.Block.ReceivedAt = msg.ReceivedAt
  595. // Mark the peer as owning the block and schedule it for import
  596. p.MarkBlock(request.Block.Hash())
  597. p.SetHead(request.Block.Hash())
  598. pm.fetcher.Enqueue(p.id, request.Block)
  599. // Update the peers total difficulty if needed, schedule a download if gapped
  600. if request.TD.Cmp(p.Td()) > 0 {
  601. p.SetTd(request.TD)
  602. td := pm.blockchain.GetTd(pm.blockchain.CurrentBlock().Hash())
  603. if request.TD.Cmp(new(big.Int).Add(td, request.Block.Difficulty())) > 0 {
  604. go pm.synchronise(p)
  605. }
  606. }
  607. case msg.Code == TxMsg:
  608. // Transactions arrived, 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.AddTransactions(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()); parent != nil {
  636. td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash()))
  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. if peer.version < eth62 {
  652. peer.SendNewBlockHashes61([]common.Hash{hash})
  653. } else {
  654. peer.SendNewBlockHashes([]common.Hash{hash}, []uint64{block.NumberU64()})
  655. }
  656. }
  657. glog.V(logger.Detail).Infof("announced block %x to %d peers in %v", hash[:4], len(peers), time.Since(block.ReceivedAt))
  658. }
  659. }
  660. // BroadcastTx will propagate a transaction to all peers which are not known to
  661. // already have the given transaction.
  662. func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *types.Transaction) {
  663. // Broadcast transaction to a batch of peers not knowing about it
  664. peers := pm.peers.PeersWithoutTx(hash)
  665. //FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))]
  666. for _, peer := range peers {
  667. peer.SendTransactions(types.Transactions{tx})
  668. }
  669. glog.V(logger.Detail).Infoln("broadcast tx to", len(peers), "peers")
  670. }
  671. // Mined broadcast loop
  672. func (self *ProtocolManager) minedBroadcastLoop() {
  673. // automatically stops if unsubscribe
  674. for obj := range self.minedBlockSub.Chan() {
  675. switch ev := obj.Data.(type) {
  676. case core.NewMinedBlockEvent:
  677. self.BroadcastBlock(ev.Block, true) // First propagate block to peers
  678. self.BroadcastBlock(ev.Block, false) // Only then announce to the rest
  679. }
  680. }
  681. }
  682. func (self *ProtocolManager) txBroadcastLoop() {
  683. // automatically stops if unsubscribe
  684. for obj := range self.txSub.Chan() {
  685. event := obj.Data.(core.TxPreEvent)
  686. self.BroadcastTx(event.Tx.Hash(), event.Tx)
  687. }
  688. }
  689. // EthNodeInfo represents a short summary of the Ethereum sub-protocol metadata known
  690. // about the host peer.
  691. type EthNodeInfo struct {
  692. Network int `json:"network"` // Ethereum network ID (0=Olympic, 1=Frontier, 2=Morden)
  693. Difficulty *big.Int `json:"difficulty"` // Total difficulty of the host's blockchain
  694. Genesis common.Hash `json:"genesis"` // SHA3 hash of the host's genesis block
  695. Head common.Hash `json:"head"` // SHA3 hash of the host's best owned block
  696. }
  697. // NodeInfo retrieves some protocol metadata about the running host node.
  698. func (self *ProtocolManager) NodeInfo() *EthNodeInfo {
  699. return &EthNodeInfo{
  700. Network: self.networkId,
  701. Difficulty: self.blockchain.GetTd(self.blockchain.CurrentBlock().Hash()),
  702. Genesis: self.blockchain.Genesis().Hash(),
  703. Head: self.blockchain.CurrentBlock().Hash(),
  704. }
  705. }