handler.go 27 KB

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