handler.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. "fmt"
  19. "math"
  20. "math/big"
  21. "sync"
  22. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/eth/downloader"
  27. "github.com/ethereum/go-ethereum/eth/fetcher"
  28. "github.com/ethereum/go-ethereum/event"
  29. "github.com/ethereum/go-ethereum/logger"
  30. "github.com/ethereum/go-ethereum/logger/glog"
  31. "github.com/ethereum/go-ethereum/p2p"
  32. "github.com/ethereum/go-ethereum/pow"
  33. "github.com/ethereum/go-ethereum/rlp"
  34. )
  35. // This is the target maximum size of returned blocks for the
  36. // getBlocks message. The reply message may exceed it
  37. // if a single block is larger than the limit.
  38. const maxBlockRespSize = 2 * 1024 * 1024
  39. func errResp(code errCode, format string, v ...interface{}) error {
  40. return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...))
  41. }
  42. type hashFetcherFn func(common.Hash) error
  43. type blockFetcherFn func([]common.Hash) error
  44. // extProt is an interface which is passed around so we can expose GetHashes and GetBlock without exposing it to the rest of the protocol
  45. // extProt is passed around to peers which require to GetHashes and GetBlocks
  46. type extProt struct {
  47. getHashes hashFetcherFn
  48. getBlocks blockFetcherFn
  49. }
  50. func (ep extProt) GetHashes(hash common.Hash) error { return ep.getHashes(hash) }
  51. func (ep extProt) GetBlock(hashes []common.Hash) error { return ep.getBlocks(hashes) }
  52. type ProtocolManager struct {
  53. protVer, netId int
  54. txpool txPool
  55. chainman *core.ChainManager
  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(networkId int, mux *event.TypeMux, txpool txPool, pow pow.PoW, chainman *core.ChainManager) *ProtocolManager {
  75. // Create the protocol manager with the base fields
  76. manager := &ProtocolManager{
  77. eventMux: mux,
  78. txpool: txpool,
  79. chainman: chainman,
  80. peers: newPeerSet(),
  81. newPeerCh: make(chan *peer, 1),
  82. txsyncCh: make(chan *txsync),
  83. quitSync: make(chan struct{}),
  84. netId: networkId,
  85. }
  86. // Initiate a sub-protocol for every implemented version we can handle
  87. manager.SubProtocols = make([]p2p.Protocol, len(ProtocolVersions))
  88. for i := 0; i < len(manager.SubProtocols); i++ {
  89. version := ProtocolVersions[i]
  90. manager.SubProtocols[i] = p2p.Protocol{
  91. Name: "eth",
  92. Version: version,
  93. Length: ProtocolLengths[i],
  94. Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
  95. peer := manager.newPeer(int(version), networkId, p, rw)
  96. manager.newPeerCh <- peer
  97. return manager.handle(peer)
  98. },
  99. }
  100. }
  101. // Construct the different synchronisation mechanisms
  102. manager.downloader = downloader.New(manager.eventMux, manager.chainman.HasBlock, manager.chainman.GetBlock, manager.chainman.CurrentBlock, manager.chainman.InsertChain, manager.removePeer)
  103. validator := func(block *types.Block, parent *types.Block) error {
  104. return core.ValidateHeader(pow, block.Header(), parent, true)
  105. }
  106. heighter := func() uint64 {
  107. return manager.chainman.CurrentBlock().NumberU64()
  108. }
  109. manager.fetcher = fetcher.New(manager.chainman.GetBlock, validator, manager.BroadcastBlock, heighter, manager.chainman.InsertChain, manager.removePeer)
  110. return manager
  111. }
  112. func (pm *ProtocolManager) removePeer(id string) {
  113. // Short circuit if the peer was already removed
  114. peer := pm.peers.Peer(id)
  115. if peer == nil {
  116. return
  117. }
  118. glog.V(logger.Debug).Infoln("Removing peer", id)
  119. // Unregister the peer from the downloader and Ethereum peer set
  120. pm.downloader.UnregisterPeer(id)
  121. if err := pm.peers.Unregister(id); err != nil {
  122. glog.V(logger.Error).Infoln("Removal failed:", err)
  123. }
  124. // Hard disconnect at the networking layer
  125. if peer != nil {
  126. peer.Peer.Disconnect(p2p.DiscUselessPeer)
  127. }
  128. }
  129. func (pm *ProtocolManager) Start() {
  130. // broadcast transactions
  131. pm.txSub = pm.eventMux.Subscribe(core.TxPreEvent{})
  132. go pm.txBroadcastLoop()
  133. // broadcast mined blocks
  134. pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
  135. go pm.minedBroadcastLoop()
  136. // start sync handlers
  137. go pm.syncer()
  138. go pm.txsyncLoop()
  139. }
  140. func (pm *ProtocolManager) Stop() {
  141. // Showing a log message. During download / process this could actually
  142. // take between 5 to 10 seconds and therefor feedback is required.
  143. glog.V(logger.Info).Infoln("Stopping ethereum protocol handler...")
  144. pm.quit = true
  145. pm.txSub.Unsubscribe() // quits txBroadcastLoop
  146. pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
  147. close(pm.quitSync) // quits syncer, fetcher, txsyncLoop
  148. // Wait for any process action
  149. pm.wg.Wait()
  150. glog.V(logger.Info).Infoln("Ethereum protocol handler stopped")
  151. }
  152. func (pm *ProtocolManager) newPeer(pv, nv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
  153. return newPeer(pv, nv, p, newMeteredMsgWriter(rw))
  154. }
  155. // handle is the callback invoked to manage the life cycle of an eth peer. When
  156. // this function terminates, the peer is disconnected.
  157. func (pm *ProtocolManager) handle(p *peer) error {
  158. glog.V(logger.Debug).Infof("%v: peer connected [%s]", p, p.Name())
  159. // Execute the Ethereum handshake
  160. td, head, genesis := pm.chainman.Status()
  161. if err := p.Handshake(td, head, genesis); err != nil {
  162. glog.V(logger.Debug).Infof("%v: handshake failed: %v", p, err)
  163. return err
  164. }
  165. // Register the peer locally
  166. glog.V(logger.Detail).Infof("%v: adding peer", p)
  167. if err := pm.peers.Register(p); err != nil {
  168. glog.V(logger.Error).Infof("%v: addition failed: %v", p, err)
  169. return err
  170. }
  171. defer pm.removePeer(p.id)
  172. // Register the peer in the downloader. If the downloader considers it banned, we disconnect
  173. if err := pm.downloader.RegisterPeer(p.id, p.version, p.Head(), p.RequestHashes, p.RequestHashesFromNumber, p.RequestBlocks); err != nil {
  174. return err
  175. }
  176. // Propagate existing transactions. new transactions appearing
  177. // after this will be sent via broadcasts.
  178. pm.syncTransactions(p)
  179. // main loop. handle incoming messages.
  180. for {
  181. if err := pm.handleMsg(p); err != nil {
  182. glog.V(logger.Debug).Infof("%v: message handling failed: %v", p, err)
  183. return err
  184. }
  185. }
  186. return nil
  187. }
  188. // handleMsg is invoked whenever an inbound message is received from a remote
  189. // peer. The remote connection is torn down upon returning any error.
  190. func (pm *ProtocolManager) handleMsg(p *peer) error {
  191. // Read the next message from the remote peer, and ensure it's fully consumed
  192. msg, err := p.rw.ReadMsg()
  193. if err != nil {
  194. return err
  195. }
  196. if msg.Size > ProtocolMaxMsgSize {
  197. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  198. }
  199. defer msg.Discard()
  200. // Handle the message depending on its contents
  201. switch msg.Code {
  202. case StatusMsg:
  203. // Status messages should never arrive after the handshake
  204. return errResp(ErrExtraStatusMsg, "uncontrolled status message")
  205. case GetBlockHashesMsg:
  206. // Retrieve the number of hashes to return and from which origin hash
  207. var request getBlockHashesData
  208. if err := msg.Decode(&request); err != nil {
  209. return errResp(ErrDecode, "%v: %v", msg, err)
  210. }
  211. if request.Amount > uint64(downloader.MaxHashFetch) {
  212. request.Amount = uint64(downloader.MaxHashFetch)
  213. }
  214. // Retrieve the hashes from the block chain and return them
  215. hashes := pm.chainman.GetBlockHashesFromHash(request.Hash, request.Amount)
  216. if len(hashes) == 0 {
  217. glog.V(logger.Debug).Infof("invalid block hash %x", request.Hash.Bytes()[:4])
  218. }
  219. return p.SendBlockHashes(hashes)
  220. case GetBlockHashesFromNumberMsg:
  221. // Retrieve and decode the number of hashes to return and from which origin number
  222. var request getBlockHashesFromNumberData
  223. if err := msg.Decode(&request); err != nil {
  224. return errResp(ErrDecode, "%v: %v", msg, err)
  225. }
  226. if request.Amount > uint64(downloader.MaxHashFetch) {
  227. request.Amount = uint64(downloader.MaxHashFetch)
  228. }
  229. // Calculate the last block that should be retrieved, and short circuit if unavailable
  230. last := pm.chainman.GetBlockByNumber(request.Number + request.Amount - 1)
  231. if last == nil {
  232. last = pm.chainman.CurrentBlock()
  233. request.Amount = last.NumberU64() - request.Number + 1
  234. }
  235. if last.NumberU64() < request.Number {
  236. return p.SendBlockHashes(nil)
  237. }
  238. // Retrieve the hashes from the last block backwards, reverse and return
  239. hashes := []common.Hash{last.Hash()}
  240. hashes = append(hashes, pm.chainman.GetBlockHashesFromHash(last.Hash(), request.Amount-1)...)
  241. for i := 0; i < len(hashes)/2; i++ {
  242. hashes[i], hashes[len(hashes)-1-i] = hashes[len(hashes)-1-i], hashes[i]
  243. }
  244. return p.SendBlockHashes(hashes)
  245. case BlockHashesMsg:
  246. // A batch of hashes arrived to one of our previous requests
  247. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  248. var hashes []common.Hash
  249. if err := msgStream.Decode(&hashes); err != nil {
  250. break
  251. }
  252. // Deliver them all to the downloader for queuing
  253. err := pm.downloader.DeliverHashes(p.id, hashes)
  254. if err != nil {
  255. glog.V(logger.Debug).Infoln(err)
  256. }
  257. case GetBlocksMsg:
  258. // Decode the retrieval message
  259. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  260. if _, err := msgStream.List(); err != nil {
  261. return err
  262. }
  263. // Gather blocks until the fetch or network limits is reached
  264. var (
  265. hash common.Hash
  266. bytes common.StorageSize
  267. hashes []common.Hash
  268. blocks []*types.Block
  269. )
  270. for {
  271. err := msgStream.Decode(&hash)
  272. if err == rlp.EOL {
  273. break
  274. } else if err != nil {
  275. return errResp(ErrDecode, "msg %v: %v", msg, err)
  276. }
  277. hashes = append(hashes, hash)
  278. // Retrieve the requested block, stopping if enough was found
  279. if block := pm.chainman.GetBlock(hash); block != nil {
  280. blocks = append(blocks, block)
  281. bytes += block.Size()
  282. if len(blocks) >= downloader.MaxBlockFetch || bytes > maxBlockRespSize {
  283. break
  284. }
  285. }
  286. }
  287. if glog.V(logger.Detail) && len(blocks) == 0 && len(hashes) > 0 {
  288. list := "["
  289. for _, hash := range hashes {
  290. list += fmt.Sprintf("%x, ", hash[:4])
  291. }
  292. list = list[:len(list)-2] + "]"
  293. glog.Infof("%v: no blocks found for requested hashes %s", p, list)
  294. }
  295. return p.SendBlocks(blocks)
  296. case BlocksMsg:
  297. // Decode the arrived block message
  298. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  299. var blocks []*types.Block
  300. if err := msgStream.Decode(&blocks); err != nil {
  301. glog.V(logger.Detail).Infoln("Decode error", err)
  302. blocks = nil
  303. }
  304. // Update the receive timestamp of each block
  305. for _, block := range blocks {
  306. block.ReceivedAt = msg.ReceivedAt
  307. }
  308. // Filter out any explicitly requested blocks, deliver the rest to the downloader
  309. if blocks := pm.fetcher.Filter(blocks); len(blocks) > 0 {
  310. pm.downloader.DeliverBlocks(p.id, blocks)
  311. }
  312. case NewBlockHashesMsg:
  313. // Retrieve and deseralize the remote new block hashes notification
  314. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  315. var hashes []common.Hash
  316. if err := msgStream.Decode(&hashes); err != nil {
  317. break
  318. }
  319. // Mark the hashes as present at the remote node
  320. for _, hash := range hashes {
  321. p.MarkBlock(hash)
  322. p.SetHead(hash)
  323. }
  324. // Schedule all the unknown hashes for retrieval
  325. unknown := make([]common.Hash, 0, len(hashes))
  326. for _, hash := range hashes {
  327. if !pm.chainman.HasBlock(hash) {
  328. unknown = append(unknown, hash)
  329. }
  330. }
  331. for _, hash := range unknown {
  332. pm.fetcher.Notify(p.id, hash, time.Now(), p.RequestBlocks)
  333. }
  334. case NewBlockMsg:
  335. // Retrieve and decode the propagated block
  336. var request newBlockData
  337. if err := msg.Decode(&request); err != nil {
  338. return errResp(ErrDecode, "%v: %v", msg, err)
  339. }
  340. if err := request.Block.ValidateFields(); err != nil {
  341. return errResp(ErrDecode, "block validation %v: %v", msg, err)
  342. }
  343. request.Block.ReceivedAt = msg.ReceivedAt
  344. // Mark the block's arrival for whatever reason
  345. _, chainHead, _ := pm.chainman.Status()
  346. jsonlogger.LogJson(&logger.EthChainReceivedNewBlock{
  347. BlockHash: request.Block.Hash().Hex(),
  348. BlockNumber: request.Block.Number(),
  349. ChainHeadHash: chainHead.Hex(),
  350. BlockPrevHash: request.Block.ParentHash().Hex(),
  351. RemoteId: p.ID().String(),
  352. })
  353. // Mark the peer as owning the block and schedule it for import
  354. p.MarkBlock(request.Block.Hash())
  355. p.SetHead(request.Block.Hash())
  356. pm.fetcher.Enqueue(p.id, request.Block)
  357. // Update the peers total difficulty if needed, schedule a download if gapped
  358. if request.TD.Cmp(p.Td()) > 0 {
  359. p.SetTd(request.TD)
  360. if request.TD.Cmp(new(big.Int).Add(pm.chainman.Td(), request.Block.Difficulty())) > 0 {
  361. go pm.synchronise(p)
  362. }
  363. }
  364. case TxMsg:
  365. // Transactions arrived, parse all of them and deliver to the pool
  366. var txs []*types.Transaction
  367. if err := msg.Decode(&txs); err != nil {
  368. return errResp(ErrDecode, "msg %v: %v", msg, err)
  369. }
  370. for i, tx := range txs {
  371. // Validate and mark the remote transaction
  372. if tx == nil {
  373. return errResp(ErrDecode, "transaction %d is nil", i)
  374. }
  375. p.MarkTransaction(tx.Hash())
  376. // Log it's arrival for later analysis
  377. jsonlogger.LogJson(&logger.EthTxReceived{
  378. TxHash: tx.Hash().Hex(),
  379. RemoteId: p.ID().String(),
  380. })
  381. }
  382. pm.txpool.AddTransactions(txs)
  383. default:
  384. return errResp(ErrInvalidMsgCode, "%v", msg.Code)
  385. }
  386. return nil
  387. }
  388. // BroadcastBlock will either propagate a block to a subset of it's peers, or
  389. // will only announce it's availability (depending what's requested).
  390. func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
  391. hash := block.Hash()
  392. peers := pm.peers.PeersWithoutBlock(hash)
  393. // If propagation is requested, send to a subset of the peer
  394. if propagate {
  395. // Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
  396. var td *big.Int
  397. if parent := pm.chainman.GetBlock(block.ParentHash()); parent != nil {
  398. td = new(big.Int).Add(parent.Td, block.Difficulty())
  399. } else {
  400. glog.V(logger.Error).Infof("propagating dangling block #%d [%x]", block.NumberU64(), hash[:4])
  401. return
  402. }
  403. // Send the block to a subset of our peers
  404. transfer := peers[:int(math.Sqrt(float64(len(peers))))]
  405. for _, peer := range transfer {
  406. peer.SendNewBlock(block, td)
  407. }
  408. glog.V(logger.Detail).Infof("propagated block %x to %d peers in %v", hash[:4], len(transfer), time.Since(block.ReceivedAt))
  409. }
  410. // Otherwise if the block is indeed in out own chain, announce it
  411. if pm.chainman.HasBlock(hash) {
  412. for _, peer := range peers {
  413. peer.SendNewBlockHashes([]common.Hash{hash})
  414. }
  415. glog.V(logger.Detail).Infof("announced block %x to %d peers in %v", hash[:4], len(peers), time.Since(block.ReceivedAt))
  416. }
  417. }
  418. // BroadcastTx will propagate a transaction to all peers which are not known to
  419. // already have the given transaction.
  420. func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *types.Transaction) {
  421. // Broadcast transaction to a batch of peers not knowing about it
  422. peers := pm.peers.PeersWithoutTx(hash)
  423. //FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))]
  424. for _, peer := range peers {
  425. peer.SendTransactions(types.Transactions{tx})
  426. }
  427. glog.V(logger.Detail).Infoln("broadcast tx to", len(peers), "peers")
  428. }
  429. // Mined broadcast loop
  430. func (self *ProtocolManager) minedBroadcastLoop() {
  431. // automatically stops if unsubscribe
  432. for obj := range self.minedBlockSub.Chan() {
  433. switch ev := obj.(type) {
  434. case core.NewMinedBlockEvent:
  435. self.BroadcastBlock(ev.Block, true) // First propagate block to peers
  436. self.BroadcastBlock(ev.Block, false) // Only then announce to the rest
  437. }
  438. }
  439. }
  440. func (self *ProtocolManager) txBroadcastLoop() {
  441. // automatically stops if unsubscribe
  442. for obj := range self.txSub.Chan() {
  443. event := obj.(core.TxPreEvent)
  444. self.BroadcastTx(event.Tx.Hash(), event.Tx)
  445. }
  446. }