handler.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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(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.HasBlock, blockchain.GetHeader, blockchain.GetBlock,
  127. blockchain.CurrentHeader, blockchain.CurrentBlock, blockchain.CurrentFastBlock, blockchain.FastSyncCommitHead, blockchain.GetTd,
  128. blockchain.InsertHeaderChain, blockchain.InsertChain, blockchain.InsertReceiptChain, blockchain.Rollback, manager.removePeer)
  129. validator := func(block *types.Block, parent *types.Block) error {
  130. return core.ValidateHeader(pow, block.Header(), parent.Header(), true, false)
  131. }
  132. heighter := func() uint64 {
  133. return blockchain.CurrentBlock().NumberU64()
  134. }
  135. manager.fetcher = fetcher.New(blockchain.GetBlock, validator, manager.BroadcastBlock, heighter, blockchain.InsertChain, manager.removePeer)
  136. return manager, nil
  137. }
  138. func (pm *ProtocolManager) removePeer(id string) {
  139. // Short circuit if the peer was already removed
  140. peer := pm.peers.Peer(id)
  141. if peer == nil {
  142. return
  143. }
  144. glog.V(logger.Debug).Infoln("Removing peer", id)
  145. // Unregister the peer from the downloader and Ethereum peer set
  146. pm.downloader.UnregisterPeer(id)
  147. if err := pm.peers.Unregister(id); err != nil {
  148. glog.V(logger.Error).Infoln("Removal failed:", err)
  149. }
  150. // Hard disconnect at the networking layer
  151. if peer != nil {
  152. peer.Peer.Disconnect(p2p.DiscUselessPeer)
  153. }
  154. }
  155. func (pm *ProtocolManager) Start() {
  156. // broadcast transactions
  157. pm.txSub = pm.eventMux.Subscribe(core.TxPreEvent{})
  158. go pm.txBroadcastLoop()
  159. // broadcast mined blocks
  160. pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
  161. go pm.minedBroadcastLoop()
  162. // start sync handlers
  163. go pm.syncer()
  164. go pm.txsyncLoop()
  165. }
  166. func (pm *ProtocolManager) Stop() {
  167. // Showing a log message. During download / process this could actually
  168. // take between 5 to 10 seconds and therefor feedback is required.
  169. glog.V(logger.Info).Infoln("Stopping ethereum protocol handler...")
  170. pm.quit = true
  171. pm.txSub.Unsubscribe() // quits txBroadcastLoop
  172. pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
  173. close(pm.quitSync) // quits syncer, fetcher, txsyncLoop
  174. // Wait for any process action
  175. pm.wg.Wait()
  176. glog.V(logger.Info).Infoln("Ethereum protocol handler stopped")
  177. }
  178. func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
  179. return newPeer(pv, p, newMeteredMsgWriter(rw))
  180. }
  181. // handle is the callback invoked to manage the life cycle of an eth peer. When
  182. // this function terminates, the peer is disconnected.
  183. func (pm *ProtocolManager) handle(p *peer) error {
  184. glog.V(logger.Debug).Infof("%v: peer connected [%s]", p, p.Name())
  185. // Execute the Ethereum handshake
  186. td, head, genesis := pm.blockchain.Status()
  187. if err := p.Handshake(pm.networkId, td, head, genesis); err != nil {
  188. glog.V(logger.Debug).Infof("%v: handshake failed: %v", p, err)
  189. return err
  190. }
  191. if rw, ok := p.rw.(*meteredMsgReadWriter); ok {
  192. rw.Init(p.version)
  193. }
  194. // Register the peer locally
  195. glog.V(logger.Detail).Infof("%v: adding peer", p)
  196. if err := pm.peers.Register(p); err != nil {
  197. glog.V(logger.Error).Infof("%v: addition failed: %v", p, err)
  198. return err
  199. }
  200. defer pm.removePeer(p.id)
  201. // Register the peer in the downloader. If the downloader considers it banned, we disconnect
  202. if err := pm.downloader.RegisterPeer(p.id, p.version, p.Head(),
  203. p.RequestHashes, p.RequestHashesFromNumber, p.RequestBlocks, p.RequestHeadersByHash,
  204. p.RequestHeadersByNumber, p.RequestBodies, p.RequestReceipts, p.RequestNodeData); err != nil {
  205. return err
  206. }
  207. // Propagate existing transactions. new transactions appearing
  208. // after this will be sent via broadcasts.
  209. pm.syncTransactions(p)
  210. // main loop. handle incoming messages.
  211. for {
  212. if err := pm.handleMsg(p); err != nil {
  213. glog.V(logger.Debug).Infof("%v: message handling failed: %v", p, err)
  214. return err
  215. }
  216. }
  217. return nil
  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. // Gather headers until the fetch or network limits is reached
  337. var (
  338. bytes common.StorageSize
  339. headers []*types.Header
  340. unknown bool
  341. )
  342. for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch {
  343. // Retrieve the next header satisfying the query
  344. var origin *types.Header
  345. if query.Origin.Hash != (common.Hash{}) {
  346. origin = pm.blockchain.GetHeader(query.Origin.Hash)
  347. } else {
  348. origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
  349. }
  350. if origin == nil {
  351. break
  352. }
  353. headers = append(headers, origin)
  354. bytes += estHeaderRlpSize
  355. // Advance to the next header of the query
  356. switch {
  357. case query.Origin.Hash != (common.Hash{}) && query.Reverse:
  358. // Hash based traversal towards the genesis block
  359. for i := 0; i < int(query.Skip)+1; i++ {
  360. if header := pm.blockchain.GetHeader(query.Origin.Hash); header != nil {
  361. query.Origin.Hash = header.ParentHash
  362. } else {
  363. unknown = true
  364. break
  365. }
  366. }
  367. case query.Origin.Hash != (common.Hash{}) && !query.Reverse:
  368. // Hash based traversal towards the leaf block
  369. if header := pm.blockchain.GetHeaderByNumber(origin.Number.Uint64() + query.Skip + 1); header != nil {
  370. if pm.blockchain.GetBlockHashesFromHash(header.Hash(), query.Skip+1)[query.Skip] == query.Origin.Hash {
  371. query.Origin.Hash = header.Hash()
  372. } else {
  373. unknown = true
  374. }
  375. } else {
  376. unknown = true
  377. }
  378. case query.Reverse:
  379. // Number based traversal towards the genesis block
  380. if query.Origin.Number >= query.Skip+1 {
  381. query.Origin.Number -= (query.Skip + 1)
  382. } else {
  383. unknown = true
  384. }
  385. case !query.Reverse:
  386. // Number based traversal towards the leaf block
  387. query.Origin.Number += (query.Skip + 1)
  388. }
  389. }
  390. return p.SendBlockHeaders(headers)
  391. case p.version >= eth62 && msg.Code == BlockHeadersMsg:
  392. // A batch of headers arrived to one of our previous requests
  393. var headers []*types.Header
  394. if err := msg.Decode(&headers); err != nil {
  395. return errResp(ErrDecode, "msg %v: %v", msg, err)
  396. }
  397. // Filter out any explicitly requested headers, deliver the rest to the downloader
  398. filter := len(headers) == 1
  399. if filter {
  400. headers = pm.fetcher.FilterHeaders(headers, time.Now())
  401. }
  402. if len(headers) > 0 || !filter {
  403. err := pm.downloader.DeliverHeaders(p.id, headers)
  404. if err != nil {
  405. glog.V(logger.Debug).Infoln(err)
  406. }
  407. }
  408. case p.version >= eth62 && msg.Code == GetBlockBodiesMsg:
  409. // Decode the retrieval message
  410. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  411. if _, err := msgStream.List(); err != nil {
  412. return err
  413. }
  414. // Gather blocks until the fetch or network limits is reached
  415. var (
  416. hash common.Hash
  417. bytes int
  418. bodies []rlp.RawValue
  419. )
  420. for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch {
  421. // Retrieve the hash of the next block
  422. if err := msgStream.Decode(&hash); err == rlp.EOL {
  423. break
  424. } else if err != nil {
  425. return errResp(ErrDecode, "msg %v: %v", msg, err)
  426. }
  427. // Retrieve the requested block body, stopping if enough was found
  428. if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 {
  429. bodies = append(bodies, data)
  430. bytes += len(data)
  431. }
  432. }
  433. return p.SendBlockBodiesRLP(bodies)
  434. case p.version >= eth62 && msg.Code == BlockBodiesMsg:
  435. // A batch of block bodies arrived to one of our previous requests
  436. var request blockBodiesData
  437. if err := msg.Decode(&request); err != nil {
  438. return errResp(ErrDecode, "msg %v: %v", msg, err)
  439. }
  440. // Deliver them all to the downloader for queuing
  441. trasactions := make([][]*types.Transaction, len(request))
  442. uncles := make([][]*types.Header, len(request))
  443. for i, body := range request {
  444. trasactions[i] = body.Transactions
  445. uncles[i] = body.Uncles
  446. }
  447. // Filter out any explicitly requested bodies, deliver the rest to the downloader
  448. if trasactions, uncles := pm.fetcher.FilterBodies(trasactions, uncles, time.Now()); len(trasactions) > 0 || len(uncles) > 0 {
  449. err := pm.downloader.DeliverBodies(p.id, trasactions, uncles)
  450. if err != nil {
  451. glog.V(logger.Debug).Infoln(err)
  452. }
  453. }
  454. case p.version >= eth63 && msg.Code == GetNodeDataMsg:
  455. // Decode the retrieval message
  456. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  457. if _, err := msgStream.List(); err != nil {
  458. return err
  459. }
  460. // Gather state data until the fetch or network limits is reached
  461. var (
  462. hash common.Hash
  463. bytes int
  464. data [][]byte
  465. )
  466. for bytes < softResponseLimit && len(data) < downloader.MaxStateFetch {
  467. // Retrieve the hash of the next state entry
  468. if err := msgStream.Decode(&hash); err == rlp.EOL {
  469. break
  470. } else if err != nil {
  471. return errResp(ErrDecode, "msg %v: %v", msg, err)
  472. }
  473. // Retrieve the requested state entry, stopping if enough was found
  474. if entry, err := pm.chaindb.Get(hash.Bytes()); err == nil {
  475. data = append(data, entry)
  476. bytes += len(entry)
  477. }
  478. }
  479. return p.SendNodeData(data)
  480. case p.version >= eth63 && msg.Code == NodeDataMsg:
  481. // A batch of node state data arrived to one of our previous requests
  482. var data [][]byte
  483. if err := msg.Decode(&data); err != nil {
  484. return errResp(ErrDecode, "msg %v: %v", msg, err)
  485. }
  486. // Deliver all to the downloader
  487. if err := pm.downloader.DeliverNodeData(p.id, data); err != nil {
  488. glog.V(logger.Debug).Infof("failed to deliver node state data: %v", err)
  489. }
  490. case p.version >= eth63 && msg.Code == GetReceiptsMsg:
  491. // Decode the retrieval message
  492. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  493. if _, err := msgStream.List(); err != nil {
  494. return err
  495. }
  496. // Gather state data until the fetch or network limits is reached
  497. var (
  498. hash common.Hash
  499. bytes int
  500. receipts []rlp.RawValue
  501. )
  502. for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch {
  503. // Retrieve the hash of the next block
  504. if err := msgStream.Decode(&hash); err == rlp.EOL {
  505. break
  506. } else if err != nil {
  507. return errResp(ErrDecode, "msg %v: %v", msg, err)
  508. }
  509. // Retrieve the requested block's receipts, skipping if unknown to us
  510. results := core.GetBlockReceipts(pm.chaindb, hash)
  511. if results == nil {
  512. if header := pm.blockchain.GetHeader(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
  513. continue
  514. }
  515. }
  516. // If known, encode and queue for response packet
  517. if encoded, err := rlp.EncodeToBytes(results); err != nil {
  518. glog.V(logger.Error).Infof("failed to encode receipt: %v", err)
  519. } else {
  520. receipts = append(receipts, encoded)
  521. bytes += len(encoded)
  522. }
  523. }
  524. return p.SendReceiptsRLP(receipts)
  525. case p.version >= eth63 && msg.Code == ReceiptsMsg:
  526. // A batch of receipts arrived to one of our previous requests
  527. var receipts [][]*types.Receipt
  528. if err := msg.Decode(&receipts); err != nil {
  529. return errResp(ErrDecode, "msg %v: %v", msg, err)
  530. }
  531. // Deliver all to the downloader
  532. if err := pm.downloader.DeliverReceipts(p.id, receipts); err != nil {
  533. glog.V(logger.Debug).Infof("failed to deliver receipts: %v", err)
  534. }
  535. case msg.Code == NewBlockHashesMsg:
  536. // Retrieve and deseralize the remote new block hashes notification
  537. type announce struct {
  538. Hash common.Hash
  539. Number uint64
  540. }
  541. var announces = []announce{}
  542. if p.version < eth62 {
  543. // We're running the old protocol, make block number unknown (0)
  544. var hashes []common.Hash
  545. if err := msg.Decode(&hashes); err != nil {
  546. return errResp(ErrDecode, "%v: %v", msg, err)
  547. }
  548. for _, hash := range hashes {
  549. announces = append(announces, announce{hash, 0})
  550. }
  551. } else {
  552. // Otherwise extract both block hash and number
  553. var request newBlockHashesData
  554. if err := msg.Decode(&request); err != nil {
  555. return errResp(ErrDecode, "%v: %v", msg, err)
  556. }
  557. for _, block := range request {
  558. announces = append(announces, announce{block.Hash, block.Number})
  559. }
  560. }
  561. // Mark the hashes as present at the remote node
  562. for _, block := range announces {
  563. p.MarkBlock(block.Hash)
  564. p.SetHead(block.Hash)
  565. }
  566. // Schedule all the unknown hashes for retrieval
  567. unknown := make([]announce, 0, len(announces))
  568. for _, block := range announces {
  569. if !pm.blockchain.HasBlock(block.Hash) {
  570. unknown = append(unknown, block)
  571. }
  572. }
  573. for _, block := range unknown {
  574. if p.version < eth62 {
  575. pm.fetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestBlocks, nil, nil)
  576. } else {
  577. pm.fetcher.Notify(p.id, block.Hash, block.Number, time.Now(), nil, p.RequestOneHeader, p.RequestBodies)
  578. }
  579. }
  580. case msg.Code == NewBlockMsg:
  581. // Retrieve and decode the propagated block
  582. var request newBlockData
  583. if err := msg.Decode(&request); err != nil {
  584. return errResp(ErrDecode, "%v: %v", msg, err)
  585. }
  586. if err := request.Block.ValidateFields(); err != nil {
  587. return errResp(ErrDecode, "block validation %v: %v", msg, err)
  588. }
  589. request.Block.ReceivedAt = msg.ReceivedAt
  590. // Mark the peer as owning the block and schedule it for import
  591. p.MarkBlock(request.Block.Hash())
  592. p.SetHead(request.Block.Hash())
  593. pm.fetcher.Enqueue(p.id, request.Block)
  594. // Update the peers total difficulty if needed, schedule a download if gapped
  595. if request.TD.Cmp(p.Td()) > 0 {
  596. p.SetTd(request.TD)
  597. td := pm.blockchain.GetTd(pm.blockchain.CurrentBlock().Hash())
  598. if request.TD.Cmp(new(big.Int).Add(td, request.Block.Difficulty())) > 0 {
  599. go pm.synchronise(p)
  600. }
  601. }
  602. case msg.Code == TxMsg:
  603. // Transactions arrived, parse all of them and deliver to the pool
  604. var txs []*types.Transaction
  605. if err := msg.Decode(&txs); err != nil {
  606. return errResp(ErrDecode, "msg %v: %v", msg, err)
  607. }
  608. for i, tx := range txs {
  609. // Validate and mark the remote transaction
  610. if tx == nil {
  611. return errResp(ErrDecode, "transaction %d is nil", i)
  612. }
  613. p.MarkTransaction(tx.Hash())
  614. }
  615. pm.txpool.AddTransactions(txs)
  616. default:
  617. return errResp(ErrInvalidMsgCode, "%v", msg.Code)
  618. }
  619. return nil
  620. }
  621. // BroadcastBlock will either propagate a block to a subset of it's peers, or
  622. // will only announce it's availability (depending what's requested).
  623. func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
  624. hash := block.Hash()
  625. peers := pm.peers.PeersWithoutBlock(hash)
  626. // If propagation is requested, send to a subset of the peer
  627. if propagate {
  628. // Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
  629. var td *big.Int
  630. if parent := pm.blockchain.GetBlock(block.ParentHash()); parent != nil {
  631. td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash()))
  632. } else {
  633. glog.V(logger.Error).Infof("propagating dangling block #%d [%x]", block.NumberU64(), hash[:4])
  634. return
  635. }
  636. // Send the block to a subset of our peers
  637. transfer := peers[:int(math.Sqrt(float64(len(peers))))]
  638. for _, peer := range transfer {
  639. peer.SendNewBlock(block, td)
  640. }
  641. glog.V(logger.Detail).Infof("propagated block %x to %d peers in %v", hash[:4], len(transfer), time.Since(block.ReceivedAt))
  642. }
  643. // Otherwise if the block is indeed in out own chain, announce it
  644. if pm.blockchain.HasBlock(hash) {
  645. for _, peer := range peers {
  646. if peer.version < eth62 {
  647. peer.SendNewBlockHashes61([]common.Hash{hash})
  648. } else {
  649. peer.SendNewBlockHashes([]common.Hash{hash}, []uint64{block.NumberU64()})
  650. }
  651. }
  652. glog.V(logger.Detail).Infof("announced block %x to %d peers in %v", hash[:4], len(peers), time.Since(block.ReceivedAt))
  653. }
  654. }
  655. // BroadcastTx will propagate a transaction to all peers which are not known to
  656. // already have the given transaction.
  657. func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *types.Transaction) {
  658. // Broadcast transaction to a batch of peers not knowing about it
  659. peers := pm.peers.PeersWithoutTx(hash)
  660. //FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))]
  661. for _, peer := range peers {
  662. peer.SendTransactions(types.Transactions{tx})
  663. }
  664. glog.V(logger.Detail).Infoln("broadcast tx to", len(peers), "peers")
  665. }
  666. // Mined broadcast loop
  667. func (self *ProtocolManager) minedBroadcastLoop() {
  668. // automatically stops if unsubscribe
  669. for obj := range self.minedBlockSub.Chan() {
  670. switch ev := obj.Data.(type) {
  671. case core.NewMinedBlockEvent:
  672. self.BroadcastBlock(ev.Block, true) // First propagate block to peers
  673. self.BroadcastBlock(ev.Block, false) // Only then announce to the rest
  674. }
  675. }
  676. }
  677. func (self *ProtocolManager) txBroadcastLoop() {
  678. // automatically stops if unsubscribe
  679. for obj := range self.txSub.Chan() {
  680. event := obj.Data.(core.TxPreEvent)
  681. self.BroadcastTx(event.Tx.Hash(), event.Tx)
  682. }
  683. }
  684. // EthNodeInfo represents a short summary of the Ethereum sub-protocol metadata known
  685. // about the host peer.
  686. type EthNodeInfo struct {
  687. Network int `json:"network"` // Ethereum network ID (0=Olympic, 1=Frontier, 2=Morden)
  688. Difficulty *big.Int `json:"difficulty"` // Total difficulty of the host's blockchain
  689. Genesis string `json:"genesis"` // SHA3 hash of the host's genesis block
  690. Head string `json:"head"` // SHA3 hash of the host's best owned block
  691. }
  692. // NodeInfo retrieves some protocol metadata about the running host node.
  693. func (self *ProtocolManager) NodeInfo() *EthNodeInfo {
  694. return &EthNodeInfo{
  695. Network: self.networkId,
  696. Difficulty: self.blockchain.GetTd(self.blockchain.CurrentBlock().Hash()),
  697. Genesis: fmt.Sprintf("%x", self.blockchain.Genesis().Hash()),
  698. Head: fmt.Sprintf("%x", self.blockchain.CurrentBlock().Hash()),
  699. }
  700. }