handler.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. package eth
  2. import (
  3. "fmt"
  4. "math"
  5. "math/big"
  6. "sync"
  7. "time"
  8. "github.com/ethereum/go-ethereum/common"
  9. "github.com/ethereum/go-ethereum/core"
  10. "github.com/ethereum/go-ethereum/core/types"
  11. "github.com/ethereum/go-ethereum/eth/downloader"
  12. "github.com/ethereum/go-ethereum/event"
  13. "github.com/ethereum/go-ethereum/logger"
  14. "github.com/ethereum/go-ethereum/logger/glog"
  15. "github.com/ethereum/go-ethereum/p2p"
  16. "github.com/ethereum/go-ethereum/rlp"
  17. )
  18. // This is the target maximum size of returned blocks for the
  19. // getBlocks message. The reply message may exceed it
  20. // if a single block is larger than the limit.
  21. const maxBlockRespSize = 2 * 1024 * 1024
  22. func errResp(code errCode, format string, v ...interface{}) error {
  23. return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...))
  24. }
  25. type hashFetcherFn func(common.Hash) error
  26. type blockFetcherFn func([]common.Hash) error
  27. // extProt is an interface which is passed around so we can expose GetHashes and GetBlock without exposing it to the rest of the protocol
  28. // extProt is passed around to peers which require to GetHashes and GetBlocks
  29. type extProt struct {
  30. getHashes hashFetcherFn
  31. getBlocks blockFetcherFn
  32. }
  33. func (ep extProt) GetHashes(hash common.Hash) error { return ep.getHashes(hash) }
  34. func (ep extProt) GetBlock(hashes []common.Hash) error { return ep.getBlocks(hashes) }
  35. type ProtocolManager struct {
  36. protVer, netId int
  37. txpool txPool
  38. chainman *core.ChainManager
  39. downloader *downloader.Downloader
  40. peers *peerSet
  41. SubProtocol p2p.Protocol
  42. eventMux *event.TypeMux
  43. txSub event.Subscription
  44. minedBlockSub event.Subscription
  45. // channels for fetcher, syncer, txsyncLoop
  46. newPeerCh chan *peer
  47. newHashCh chan []*blockAnnounce
  48. newBlockCh chan chan []*types.Block
  49. txsyncCh chan *txsync
  50. quitSync chan struct{}
  51. // wait group is used for graceful shutdowns during downloading
  52. // and processing
  53. wg sync.WaitGroup
  54. quit bool
  55. }
  56. // NewProtocolManager returns a new ethereum sub protocol manager. The Ethereum sub protocol manages peers capable
  57. // with the ethereum network.
  58. func NewProtocolManager(protocolVersion, networkId int, mux *event.TypeMux, txpool txPool, chainman *core.ChainManager) *ProtocolManager {
  59. manager := &ProtocolManager{
  60. eventMux: mux,
  61. txpool: txpool,
  62. chainman: chainman,
  63. peers: newPeerSet(),
  64. newPeerCh: make(chan *peer, 1),
  65. newHashCh: make(chan []*blockAnnounce, 1),
  66. newBlockCh: make(chan chan []*types.Block),
  67. txsyncCh: make(chan *txsync),
  68. quitSync: make(chan struct{}),
  69. }
  70. manager.downloader = downloader.New(manager.eventMux, manager.chainman.HasBlock, manager.chainman.GetBlock, manager.removePeer)
  71. manager.SubProtocol = p2p.Protocol{
  72. Name: "eth",
  73. Version: uint(protocolVersion),
  74. Length: ProtocolLength,
  75. Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
  76. peer := manager.newPeer(protocolVersion, networkId, p, rw)
  77. manager.newPeerCh <- peer
  78. return manager.handle(peer)
  79. },
  80. }
  81. return manager
  82. }
  83. func (pm *ProtocolManager) removePeer(id string) {
  84. // Short circuit if the peer was already removed
  85. peer := pm.peers.Peer(id)
  86. if peer == nil {
  87. return
  88. }
  89. glog.V(logger.Debug).Infoln("Removing peer", id)
  90. // Unregister the peer from the downloader and Ethereum peer set
  91. pm.downloader.UnregisterPeer(id)
  92. if err := pm.peers.Unregister(id); err != nil {
  93. glog.V(logger.Error).Infoln("Removal failed:", err)
  94. }
  95. // Hard disconnect at the networking layer
  96. if peer != nil {
  97. peer.Peer.Disconnect(p2p.DiscUselessPeer)
  98. }
  99. }
  100. func (pm *ProtocolManager) Start() {
  101. // broadcast transactions
  102. pm.txSub = pm.eventMux.Subscribe(core.TxPreEvent{})
  103. go pm.txBroadcastLoop()
  104. // broadcast mined blocks
  105. pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
  106. go pm.minedBroadcastLoop()
  107. // start sync handlers
  108. go pm.syncer()
  109. go pm.fetcher()
  110. go pm.txsyncLoop()
  111. }
  112. func (pm *ProtocolManager) Stop() {
  113. // Showing a log message. During download / process this could actually
  114. // take between 5 to 10 seconds and therefor feedback is required.
  115. glog.V(logger.Info).Infoln("Stopping ethereum protocol handler...")
  116. pm.quit = true
  117. pm.txSub.Unsubscribe() // quits txBroadcastLoop
  118. pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
  119. close(pm.quitSync) // quits syncer, fetcher, txsyncLoop
  120. // Wait for any process action
  121. pm.wg.Wait()
  122. glog.V(logger.Info).Infoln("Ethereum protocol handler stopped")
  123. }
  124. func (pm *ProtocolManager) newPeer(pv, nv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
  125. td, current, genesis := pm.chainman.Status()
  126. return newPeer(pv, nv, genesis, current, td, p, rw)
  127. }
  128. func (pm *ProtocolManager) handle(p *peer) error {
  129. // Execute the Ethereum handshake.
  130. if err := p.handleStatus(); err != nil {
  131. return err
  132. }
  133. // Register the peer locally.
  134. glog.V(logger.Detail).Infoln("Adding peer", p.id)
  135. if err := pm.peers.Register(p); err != nil {
  136. glog.V(logger.Error).Infoln("Addition failed:", err)
  137. return err
  138. }
  139. defer pm.removePeer(p.id)
  140. // Register the peer in the downloader. If the downloader
  141. // considers it banned, we disconnect.
  142. if err := pm.downloader.RegisterPeer(p.id, p.Head(), p.requestHashes, p.requestBlocks); err != nil {
  143. return err
  144. }
  145. // Propagate existing transactions. new transactions appearing
  146. // after this will be sent via broadcasts.
  147. pm.syncTransactions(p)
  148. // main loop. handle incoming messages.
  149. for {
  150. if err := pm.handleMsg(p); err != nil {
  151. return err
  152. }
  153. }
  154. return nil
  155. }
  156. func (self *ProtocolManager) handleMsg(p *peer) error {
  157. msg, err := p.rw.ReadMsg()
  158. if err != nil {
  159. return err
  160. }
  161. if msg.Size > ProtocolMaxMsgSize {
  162. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  163. }
  164. // make sure that the payload has been fully consumed
  165. defer msg.Discard()
  166. switch msg.Code {
  167. case StatusMsg:
  168. return errResp(ErrExtraStatusMsg, "uncontrolled status message")
  169. case TxMsg:
  170. // TODO: rework using lazy RLP stream
  171. var txs []*types.Transaction
  172. if err := msg.Decode(&txs); err != nil {
  173. return errResp(ErrDecode, "msg %v: %v", msg, err)
  174. }
  175. for i, tx := range txs {
  176. if tx == nil {
  177. return errResp(ErrDecode, "transaction %d is nil", i)
  178. }
  179. jsonlogger.LogJson(&logger.EthTxReceived{
  180. TxHash: tx.Hash().Hex(),
  181. RemoteId: p.ID().String(),
  182. })
  183. }
  184. self.txpool.AddTransactions(txs)
  185. case GetBlockHashesMsg:
  186. var request getBlockHashesMsgData
  187. if err := msg.Decode(&request); err != nil {
  188. return errResp(ErrDecode, "->msg %v: %v", msg, err)
  189. }
  190. if request.Amount > uint64(downloader.MaxHashFetch) {
  191. request.Amount = uint64(downloader.MaxHashFetch)
  192. }
  193. hashes := self.chainman.GetBlockHashesFromHash(request.Hash, request.Amount)
  194. if glog.V(logger.Debug) {
  195. if len(hashes) == 0 {
  196. glog.Infof("invalid block hash %x", request.Hash.Bytes()[:4])
  197. }
  198. }
  199. // returns either requested hashes or nothing (i.e. not found)
  200. return p.sendBlockHashes(hashes)
  201. case BlockHashesMsg:
  202. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  203. var hashes []common.Hash
  204. if err := msgStream.Decode(&hashes); err != nil {
  205. break
  206. }
  207. err := self.downloader.DeliverHashes(p.id, hashes)
  208. if err != nil {
  209. glog.V(logger.Debug).Infoln(err)
  210. }
  211. case GetBlocksMsg:
  212. var blocks []*types.Block
  213. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  214. if _, err := msgStream.List(); err != nil {
  215. return err
  216. }
  217. var (
  218. i int
  219. totalsize common.StorageSize
  220. )
  221. for {
  222. i++
  223. var hash common.Hash
  224. err := msgStream.Decode(&hash)
  225. if err == rlp.EOL {
  226. break
  227. } else if err != nil {
  228. return errResp(ErrDecode, "msg %v: %v", msg, err)
  229. }
  230. block := self.chainman.GetBlock(hash)
  231. if block != nil {
  232. blocks = append(blocks, block)
  233. totalsize += block.Size()
  234. }
  235. if i == downloader.MaxBlockFetch || totalsize > maxBlockRespSize {
  236. break
  237. }
  238. }
  239. return p.sendBlocks(blocks)
  240. case BlocksMsg:
  241. // Decode the arrived block message
  242. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  243. var blocks []*types.Block
  244. if err := msgStream.Decode(&blocks); err != nil {
  245. glog.V(logger.Detail).Infoln("Decode error", err)
  246. blocks = nil
  247. }
  248. // Filter out any explicitly requested blocks (cascading select to get blocking back to peer)
  249. filter := make(chan []*types.Block)
  250. select {
  251. case <-self.quitSync:
  252. case self.newBlockCh <- filter:
  253. select {
  254. case <-self.quitSync:
  255. case filter <- blocks:
  256. select {
  257. case <-self.quitSync:
  258. case blocks := <-filter:
  259. self.downloader.DeliverBlocks(p.id, blocks)
  260. }
  261. }
  262. }
  263. case NewBlockHashesMsg:
  264. // Retrieve and deseralize the remote new block hashes notification
  265. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  266. var hashes []common.Hash
  267. if err := msgStream.Decode(&hashes); err != nil {
  268. break
  269. }
  270. // Mark the hashes as present at the remote node
  271. for _, hash := range hashes {
  272. p.blockHashes.Add(hash)
  273. p.SetHead(hash)
  274. }
  275. // Schedule all the unknown hashes for retrieval
  276. unknown := make([]common.Hash, 0, len(hashes))
  277. for _, hash := range hashes {
  278. if !self.chainman.HasBlock(hash) {
  279. unknown = append(unknown, hash)
  280. }
  281. }
  282. announces := make([]*blockAnnounce, len(unknown))
  283. for i, hash := range unknown {
  284. announces[i] = &blockAnnounce{
  285. hash: hash,
  286. peer: p,
  287. time: time.Now(),
  288. }
  289. }
  290. if len(announces) > 0 {
  291. select {
  292. case self.newHashCh <- announces:
  293. case <-self.quitSync:
  294. }
  295. }
  296. case NewBlockMsg:
  297. var request newBlockMsgData
  298. if err := msg.Decode(&request); err != nil {
  299. return errResp(ErrDecode, "%v: %v", msg, err)
  300. }
  301. if err := request.Block.ValidateFields(); err != nil {
  302. return errResp(ErrDecode, "block validation %v: %v", msg, err)
  303. }
  304. request.Block.ReceivedAt = msg.ReceivedAt
  305. if err := self.importBlock(p, request.Block, request.TD); err != nil {
  306. return err
  307. }
  308. default:
  309. return errResp(ErrInvalidMsgCode, "%v", msg.Code)
  310. }
  311. return nil
  312. }
  313. // importBlocks injects a new block retrieved from the given peer into the chain
  314. // manager.
  315. func (pm *ProtocolManager) importBlock(p *peer, block *types.Block, td *big.Int) error {
  316. hash := block.Hash()
  317. // Mark the block as present at the remote node (don't duplicate already held data)
  318. p.blockHashes.Add(hash)
  319. p.SetHead(hash)
  320. if td != nil {
  321. p.SetTd(td)
  322. }
  323. // Log the block's arrival
  324. _, chainHead, _ := pm.chainman.Status()
  325. jsonlogger.LogJson(&logger.EthChainReceivedNewBlock{
  326. BlockHash: hash.Hex(),
  327. BlockNumber: block.Number(),
  328. ChainHeadHash: chainHead.Hex(),
  329. BlockPrevHash: block.ParentHash().Hex(),
  330. RemoteId: p.ID().String(),
  331. })
  332. // If the block's already known or its difficulty is lower than ours, drop
  333. if pm.chainman.HasBlock(hash) {
  334. p.SetTd(pm.chainman.GetBlock(hash).Td) // update the peer's TD to the real value
  335. return nil
  336. }
  337. if td != nil && pm.chainman.Td().Cmp(td) > 0 && new(big.Int).Add(block.Number(), big.NewInt(7)).Cmp(pm.chainman.CurrentBlock().Number()) < 0 {
  338. glog.V(logger.Debug).Infof("[%s] dropped block %v due to low TD %v\n", p.id, block.Number(), td)
  339. return nil
  340. }
  341. // Attempt to insert the newly received block and propagate to our peers
  342. if pm.chainman.HasBlock(block.ParentHash()) {
  343. if _, err := pm.chainman.InsertChain(types.Blocks{block}); err != nil {
  344. glog.V(logger.Error).Infoln("removed peer (", p.id, ") due to block error", err)
  345. return err
  346. }
  347. if td != nil && block.Td.Cmp(td) != 0 {
  348. err := fmt.Errorf("invalid TD on block(%v) from peer(%s): block.td=%v, request.td=%v", block.Number(), p.id, block.Td, td)
  349. glog.V(logger.Error).Infoln(err)
  350. return err
  351. }
  352. pm.BroadcastBlock(hash, block)
  353. return nil
  354. }
  355. // Parent of the block is unknown, try to sync with this peer if it seems to be good
  356. if td != nil {
  357. go pm.synchronise(p)
  358. }
  359. return nil
  360. }
  361. // BroadcastBlock will propagate the block to a subset of its connected peers,
  362. // only notifying the rest of the block's appearance.
  363. func (pm *ProtocolManager) BroadcastBlock(hash common.Hash, block *types.Block) {
  364. // Retrieve all the target peers and split between full broadcast or only notification
  365. peers := pm.peers.PeersWithoutBlock(hash)
  366. split := int(math.Sqrt(float64(len(peers))))
  367. transfer := peers[:split]
  368. notify := peers[split:]
  369. // Send out the data transfers and the notifications
  370. for _, peer := range notify {
  371. peer.sendNewBlockHashes([]common.Hash{hash})
  372. }
  373. glog.V(logger.Detail).Infoln("broadcast hash to", len(notify), "peers.")
  374. for _, peer := range transfer {
  375. peer.sendNewBlock(block)
  376. }
  377. glog.V(logger.Detail).Infoln("broadcast block to", len(transfer), "peers. Total processing time:", time.Since(block.ReceivedAt))
  378. }
  379. // BroadcastTx will propagate the block to its connected peers. It will sort
  380. // out which peers do not contain the block in their block set and will do a
  381. // sqrt(peers) to determine the amount of peers we broadcast to.
  382. func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *types.Transaction) {
  383. // Broadcast transaction to a batch of peers not knowing about it
  384. peers := pm.peers.PeersWithoutTx(hash)
  385. //FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))]
  386. for _, peer := range peers {
  387. peer.sendTransaction(tx)
  388. }
  389. glog.V(logger.Detail).Infoln("broadcast tx to", len(peers), "peers")
  390. }
  391. // Mined broadcast loop
  392. func (self *ProtocolManager) minedBroadcastLoop() {
  393. // automatically stops if unsubscribe
  394. for obj := range self.minedBlockSub.Chan() {
  395. switch ev := obj.(type) {
  396. case core.NewMinedBlockEvent:
  397. self.BroadcastBlock(ev.Block.Hash(), ev.Block)
  398. }
  399. }
  400. }
  401. func (self *ProtocolManager) txBroadcastLoop() {
  402. // automatically stops if unsubscribe
  403. for obj := range self.txSub.Chan() {
  404. event := obj.(core.TxPreEvent)
  405. self.BroadcastTx(event.Tx.Hash(), event.Tx)
  406. }
  407. }