handler.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. package eth
  2. // XXX Fair warning, most of the code is re-used from the old protocol. Please be aware that most of this will actually change
  3. // The idea is that most of the calls within the protocol will become synchronous.
  4. // Block downloading and block processing will be complete seperate processes
  5. /*
  6. # Possible scenarios
  7. // Synching scenario
  8. // Use the best peer to synchronise
  9. blocks, err := pm.downloader.Synchronise()
  10. if err != nil {
  11. // handle
  12. break
  13. }
  14. pm.chainman.InsertChain(blocks)
  15. // Receiving block with known parent
  16. if parent_exist {
  17. if err := pm.chainman.InsertChain(block); err != nil {
  18. // handle
  19. break
  20. }
  21. pm.BroadcastBlock(block)
  22. }
  23. // Receiving block with unknown parent
  24. blocks, err := pm.downloader.SynchroniseWithPeer(peer)
  25. if err != nil {
  26. // handle
  27. break
  28. }
  29. pm.chainman.InsertChain(blocks)
  30. */
  31. import (
  32. "fmt"
  33. "math"
  34. "math/big"
  35. "sync"
  36. "time"
  37. "github.com/ethereum/go-ethereum/common"
  38. "github.com/ethereum/go-ethereum/core"
  39. "github.com/ethereum/go-ethereum/core/types"
  40. "github.com/ethereum/go-ethereum/eth/downloader"
  41. "github.com/ethereum/go-ethereum/event"
  42. "github.com/ethereum/go-ethereum/logger"
  43. "github.com/ethereum/go-ethereum/logger/glog"
  44. "github.com/ethereum/go-ethereum/p2p"
  45. "github.com/ethereum/go-ethereum/rlp"
  46. )
  47. const (
  48. peerCountTimeout = 12 * time.Second // Amount of time it takes for the peer handler to ignore minDesiredPeerCount
  49. minDesiredPeerCount = 5 // Amount of peers desired to start syncing
  50. )
  51. func errResp(code errCode, format string, v ...interface{}) error {
  52. return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...))
  53. }
  54. type hashFetcherFn func(common.Hash) error
  55. type blockFetcherFn func([]common.Hash) error
  56. // extProt is an interface which is passed around so we can expose GetHashes and GetBlock without exposing it to the rest of the protocol
  57. // extProt is passed around to peers which require to GetHashes and GetBlocks
  58. type extProt struct {
  59. getHashes hashFetcherFn
  60. getBlocks blockFetcherFn
  61. }
  62. func (ep extProt) GetHashes(hash common.Hash) error { return ep.getHashes(hash) }
  63. func (ep extProt) GetBlock(hashes []common.Hash) error { return ep.getBlocks(hashes) }
  64. type ProtocolManager struct {
  65. protVer, netId int
  66. txpool txPool
  67. chainman *core.ChainManager
  68. downloader *downloader.Downloader
  69. pmu sync.Mutex
  70. peers map[string]*peer
  71. SubProtocol p2p.Protocol
  72. eventMux *event.TypeMux
  73. txSub event.Subscription
  74. minedBlockSub event.Subscription
  75. newPeerCh chan *peer
  76. quitSync chan struct{}
  77. }
  78. // NewProtocolManager returns a new ethereum sub protocol manager. The Ethereum sub protocol manages peers capable
  79. // with the ethereum network.
  80. func NewProtocolManager(protocolVersion, networkId int, mux *event.TypeMux, txpool txPool, chainman *core.ChainManager, downloader *downloader.Downloader) *ProtocolManager {
  81. manager := &ProtocolManager{
  82. eventMux: mux,
  83. txpool: txpool,
  84. chainman: chainman,
  85. downloader: downloader,
  86. peers: make(map[string]*peer),
  87. newPeerCh: make(chan *peer, 1),
  88. quitSync: make(chan struct{}),
  89. }
  90. manager.SubProtocol = p2p.Protocol{
  91. Name: "eth",
  92. Version: uint(protocolVersion),
  93. Length: ProtocolLength,
  94. Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
  95. peer := manager.newPeer(protocolVersion, networkId, p, rw)
  96. manager.newPeerCh <- peer
  97. return manager.handle(peer)
  98. },
  99. }
  100. return manager
  101. }
  102. func (pm *ProtocolManager) syncHandler() {
  103. // itimer is used to determine when to start ignoring `minDesiredPeerCount`
  104. itimer := time.NewTimer(peerCountTimeout)
  105. out:
  106. for {
  107. select {
  108. case <-pm.newPeerCh:
  109. // Meet the `minDesiredPeerCount` before we select our best peer
  110. if len(pm.peers) < minDesiredPeerCount {
  111. break
  112. }
  113. // Find the best peer
  114. peer := getBestPeer(pm.peers)
  115. if peer == nil {
  116. glog.V(logger.Debug).Infoln("Sync attempt cancelled. No peers available")
  117. }
  118. itimer.Stop()
  119. go pm.synchronise(peer)
  120. case <-itimer.C:
  121. // The timer will make sure that the downloader keeps an active state
  122. // in which it attempts to always check the network for highest td peers
  123. // Either select the peer or restart the timer if no peers could
  124. // be selected.
  125. if peer := getBestPeer(pm.peers); peer != nil {
  126. go pm.synchronise(peer)
  127. } else {
  128. itimer.Reset(5 * time.Second)
  129. }
  130. case <-pm.quitSync:
  131. break out
  132. }
  133. }
  134. }
  135. func (pm *ProtocolManager) synchronise(peer *peer) {
  136. // Make sure the peer's TD is higher than our own. If not drop.
  137. if peer.td.Cmp(pm.chainman.Td()) <= 0 {
  138. return
  139. }
  140. // Check downloader if it's busy so it doesn't show the sync message
  141. // for every attempty
  142. if pm.downloader.IsBusy() {
  143. return
  144. }
  145. glog.V(logger.Info).Infof("Synchronisation attempt using %s TD=%v\n", peer.id, peer.td)
  146. // Get the hashes from the peer (synchronously)
  147. err := pm.downloader.Synchronise(peer.id, peer.recentHash)
  148. if err != nil {
  149. // handle error
  150. glog.V(logger.Debug).Infoln("error downloading:", err)
  151. }
  152. }
  153. func (pm *ProtocolManager) Start() {
  154. // broadcast transactions
  155. pm.txSub = pm.eventMux.Subscribe(core.TxPreEvent{})
  156. go pm.txBroadcastLoop()
  157. // broadcast mined blocks
  158. pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
  159. go pm.minedBroadcastLoop()
  160. // sync handler
  161. go pm.syncHandler()
  162. }
  163. func (pm *ProtocolManager) Stop() {
  164. pm.txSub.Unsubscribe() // quits txBroadcastLoop
  165. pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
  166. close(pm.quitSync) // quits the sync handler
  167. }
  168. func (pm *ProtocolManager) newPeer(pv, nv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
  169. td, current, genesis := pm.chainman.Status()
  170. return newPeer(pv, nv, genesis, current, td, p, rw)
  171. }
  172. func (pm *ProtocolManager) handle(p *peer) error {
  173. if err := p.handleStatus(); err != nil {
  174. return err
  175. }
  176. pm.pmu.Lock()
  177. pm.peers[p.id] = p
  178. pm.pmu.Unlock()
  179. pm.downloader.RegisterPeer(p.id, p.recentHash, p.requestHashes, p.requestBlocks)
  180. defer func() {
  181. pm.pmu.Lock()
  182. defer pm.pmu.Unlock()
  183. delete(pm.peers, p.id)
  184. pm.downloader.UnregisterPeer(p.id)
  185. }()
  186. // propagate existing transactions. new transactions appearing
  187. // after this will be sent via broadcasts.
  188. if err := p.sendTransactions(pm.txpool.GetTransactions()); err != nil {
  189. return err
  190. }
  191. // main loop. handle incoming messages.
  192. for {
  193. if err := pm.handleMsg(p); err != nil {
  194. return err
  195. }
  196. }
  197. return nil
  198. }
  199. func (self *ProtocolManager) handleMsg(p *peer) error {
  200. msg, err := p.rw.ReadMsg()
  201. if err != nil {
  202. return err
  203. }
  204. if msg.Size > ProtocolMaxMsgSize {
  205. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  206. }
  207. // make sure that the payload has been fully consumed
  208. defer msg.Discard()
  209. switch msg.Code {
  210. case GetTxMsg: // ignore
  211. case StatusMsg:
  212. return errResp(ErrExtraStatusMsg, "uncontrolled status message")
  213. case TxMsg:
  214. // TODO: rework using lazy RLP stream
  215. var txs []*types.Transaction
  216. if err := msg.Decode(&txs); err != nil {
  217. return errResp(ErrDecode, "msg %v: %v", msg, err)
  218. }
  219. for i, tx := range txs {
  220. if tx == nil {
  221. return errResp(ErrDecode, "transaction %d is nil", i)
  222. }
  223. jsonlogger.LogJson(&logger.EthTxReceived{
  224. TxHash: tx.Hash().Hex(),
  225. RemoteId: p.ID().String(),
  226. })
  227. }
  228. self.txpool.AddTransactions(txs)
  229. case GetBlockHashesMsg:
  230. var request getBlockHashesMsgData
  231. if err := msg.Decode(&request); err != nil {
  232. return errResp(ErrDecode, "->msg %v: %v", msg, err)
  233. }
  234. if request.Amount > maxHashes {
  235. request.Amount = maxHashes
  236. }
  237. hashes := self.chainman.GetBlockHashesFromHash(request.Hash, request.Amount)
  238. if glog.V(logger.Debug) {
  239. if len(hashes) == 0 {
  240. glog.Infof("invalid block hash %x", request.Hash.Bytes()[:4])
  241. }
  242. }
  243. // returns either requested hashes or nothing (i.e. not found)
  244. return p.sendBlockHashes(hashes)
  245. case BlockHashesMsg:
  246. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  247. var hashes []common.Hash
  248. if err := msgStream.Decode(&hashes); err != nil {
  249. break
  250. }
  251. err := self.downloader.AddHashes(p.id, hashes)
  252. if err != nil {
  253. glog.V(logger.Debug).Infoln(err)
  254. }
  255. case GetBlocksMsg:
  256. var blocks []*types.Block
  257. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  258. if _, err := msgStream.List(); err != nil {
  259. return err
  260. }
  261. var i int
  262. for {
  263. i++
  264. var hash common.Hash
  265. err := msgStream.Decode(&hash)
  266. if err == rlp.EOL {
  267. break
  268. } else if err != nil {
  269. return errResp(ErrDecode, "msg %v: %v", msg, err)
  270. }
  271. block := self.chainman.GetBlock(hash)
  272. if block != nil {
  273. blocks = append(blocks, block)
  274. }
  275. if i == maxBlocks {
  276. break
  277. }
  278. }
  279. return p.sendBlocks(blocks)
  280. case BlocksMsg:
  281. var blocks []*types.Block
  282. msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
  283. if err := msgStream.Decode(&blocks); err != nil {
  284. glog.V(logger.Detail).Infoln("Decode error", err)
  285. blocks = nil
  286. }
  287. self.downloader.DeliverChunk(p.id, blocks)
  288. case NewBlockMsg:
  289. var request newBlockMsgData
  290. if err := msg.Decode(&request); err != nil {
  291. return errResp(ErrDecode, "%v: %v", msg, err)
  292. }
  293. if err := request.Block.ValidateFields(); err != nil {
  294. return errResp(ErrDecode, "block validation %v: %v", msg, err)
  295. }
  296. request.Block.ReceivedAt = time.Now()
  297. hash := request.Block.Hash()
  298. // Add the block hash as a known hash to the peer. This will later be used to determine
  299. // who should receive this.
  300. p.blockHashes.Add(hash)
  301. _, chainHead, _ := self.chainman.Status()
  302. jsonlogger.LogJson(&logger.EthChainReceivedNewBlock{
  303. BlockHash: hash.Hex(),
  304. BlockNumber: request.Block.Number(), // this surely must be zero
  305. ChainHeadHash: chainHead.Hex(),
  306. BlockPrevHash: request.Block.ParentHash().Hex(),
  307. RemoteId: p.ID().String(),
  308. })
  309. // Make sure the block isn't already known. If this is the case simply drop
  310. // the message and move on. If the TD is < currentTd; drop it as well. If this
  311. // chain at some point becomes canonical, the downloader will fetch it.
  312. if self.chainman.HasBlock(hash) {
  313. break
  314. }
  315. if self.chainman.Td().Cmp(request.TD) > 0 && new(big.Int).Add(request.Block.Number(), big.NewInt(7)).Cmp(self.chainman.CurrentBlock().Number()) < 0 {
  316. glog.V(logger.Debug).Infof("[%s] dropped block %v due to low TD %v\n", p.id, request.Block.Number(), request.TD)
  317. break
  318. }
  319. // Attempt to insert the newly received by checking if the parent exists.
  320. // if the parent exists we process the block and propagate to our peers
  321. // if the parent does not exists we delegate to the downloader.
  322. if self.chainman.HasBlock(request.Block.ParentHash()) {
  323. if _, err := self.chainman.InsertChain(types.Blocks{request.Block}); err != nil {
  324. // handle error
  325. return nil
  326. }
  327. self.BroadcastBlock(hash, request.Block)
  328. } else {
  329. // adding blocks is synchronous
  330. go func() {
  331. // TODO check parent error
  332. err := self.downloader.AddBlock(p.id, request.Block, request.TD)
  333. if err != nil {
  334. glog.V(logger.Detail).Infoln("downloader err:", err)
  335. return
  336. }
  337. self.BroadcastBlock(hash, request.Block)
  338. }()
  339. }
  340. default:
  341. return errResp(ErrInvalidMsgCode, "%v", msg.Code)
  342. }
  343. return nil
  344. }
  345. // BroadcastBlock will propagate the block to its connected peers. It will sort
  346. // out which peers do not contain the block in their block set and will do a
  347. // sqrt(peers) to determine the amount of peers we broadcast to.
  348. func (pm *ProtocolManager) BroadcastBlock(hash common.Hash, block *types.Block) {
  349. pm.pmu.Lock()
  350. defer pm.pmu.Unlock()
  351. // Find peers who don't know anything about the given hash. Peers that
  352. // don't know about the hash will be a candidate for the broadcast loop
  353. var peers []*peer
  354. for _, peer := range pm.peers {
  355. if !peer.blockHashes.Has(hash) {
  356. peers = append(peers, peer)
  357. }
  358. }
  359. // Broadcast block to peer set
  360. peers = peers[:int(math.Sqrt(float64(len(peers))))]
  361. for _, peer := range peers {
  362. peer.sendNewBlock(block)
  363. }
  364. glog.V(logger.Detail).Infoln("broadcast block to", len(peers), "peers. Total propagation time:", time.Since(block.ReceivedAt))
  365. }
  366. // BroadcastTx will propagate the block to its connected peers. It will sort
  367. // out which peers do not contain the block in their block set and will do a
  368. // sqrt(peers) to determine the amount of peers we broadcast to.
  369. func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *types.Transaction) {
  370. pm.pmu.Lock()
  371. defer pm.pmu.Unlock()
  372. // Find peers who don't know anything about the given hash. Peers that
  373. // don't know about the hash will be a candidate for the broadcast loop
  374. var peers []*peer
  375. for _, peer := range pm.peers {
  376. if !peer.txHashes.Has(hash) {
  377. peers = append(peers, peer)
  378. }
  379. }
  380. // Broadcast block to peer set
  381. peers = peers[:int(math.Sqrt(float64(len(peers))))]
  382. for _, peer := range peers {
  383. peer.sendTransaction(tx)
  384. }
  385. glog.V(logger.Detail).Infoln("broadcast tx to", len(peers), "peers")
  386. }
  387. // Mined broadcast loop
  388. func (self *ProtocolManager) minedBroadcastLoop() {
  389. // automatically stops if unsubscribe
  390. for obj := range self.minedBlockSub.Chan() {
  391. switch ev := obj.(type) {
  392. case core.NewMinedBlockEvent:
  393. self.BroadcastBlock(ev.Block.Hash(), ev.Block)
  394. }
  395. }
  396. }
  397. func (self *ProtocolManager) txBroadcastLoop() {
  398. // automatically stops if unsubscribe
  399. for obj := range self.txSub.Chan() {
  400. event := obj.(core.TxPreEvent)
  401. self.BroadcastTx(event.Tx.Hash(), event.Tx)
  402. }
  403. }