protocol.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. package eth
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "math/big"
  7. "github.com/ethereum/go-ethereum/core/types"
  8. "github.com/ethereum/go-ethereum/ethutil"
  9. "github.com/ethereum/go-ethereum/logger"
  10. "github.com/ethereum/go-ethereum/p2p"
  11. "github.com/ethereum/go-ethereum/rlp"
  12. )
  13. const (
  14. ProtocolVersion = 54
  15. NetworkId = 0
  16. ProtocolLength = uint64(8)
  17. ProtocolMaxMsgSize = 10 * 1024 * 1024
  18. )
  19. // eth protocol message codes
  20. const (
  21. StatusMsg = iota
  22. GetTxMsg // unused
  23. TxMsg
  24. GetBlockHashesMsg
  25. BlockHashesMsg
  26. GetBlocksMsg
  27. BlocksMsg
  28. NewBlockMsg
  29. )
  30. // ethProtocol represents the ethereum wire protocol
  31. // instance is running on each peer
  32. type ethProtocol struct {
  33. txPool txPool
  34. chainManager chainManager
  35. blockPool blockPool
  36. peer *p2p.Peer
  37. id string
  38. rw p2p.MsgReadWriter
  39. }
  40. // backend is the interface the ethereum protocol backend should implement
  41. // used as an argument to EthProtocol
  42. type txPool interface {
  43. AddTransactions([]*types.Transaction)
  44. GetTransactions() types.Transactions
  45. }
  46. type chainManager interface {
  47. GetBlockHashesFromHash(hash []byte, amount uint64) (hashes [][]byte)
  48. GetBlock(hash []byte) (block *types.Block)
  49. Status() (td *big.Int, currentBlock []byte, genesisBlock []byte)
  50. }
  51. type blockPool interface {
  52. AddBlockHashes(next func() ([]byte, bool), peerId string)
  53. AddBlock(block *types.Block, peerId string)
  54. AddPeer(td *big.Int, currentBlock []byte, peerId string, requestHashes func([]byte) error, requestBlocks func([][]byte) error, peerError func(int, string, ...interface{})) (best bool)
  55. RemovePeer(peerId string)
  56. }
  57. // message structs used for rlp decoding
  58. type newBlockMsgData struct {
  59. Block *types.Block
  60. TD *big.Int
  61. }
  62. const maxHashes = 255
  63. type getBlockHashesMsgData struct {
  64. Hash []byte
  65. Amount uint64
  66. }
  67. // main entrypoint, wrappers starting a server running the eth protocol
  68. // use this constructor to attach the protocol ("class") to server caps
  69. // the Dev p2p layer then runs the protocol instance on each peer
  70. func EthProtocol(txPool txPool, chainManager chainManager, blockPool blockPool) p2p.Protocol {
  71. return p2p.Protocol{
  72. Name: "eth",
  73. Version: ProtocolVersion,
  74. Length: ProtocolLength,
  75. Run: func(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
  76. return runEthProtocol(txPool, chainManager, blockPool, peer, rw)
  77. },
  78. }
  79. }
  80. // the main loop that handles incoming messages
  81. // note RemovePeer in the post-disconnect hook
  82. func runEthProtocol(txPool txPool, chainManager chainManager, blockPool blockPool, peer *p2p.Peer, rw p2p.MsgReadWriter) (err error) {
  83. id := peer.ID()
  84. self := &ethProtocol{
  85. txPool: txPool,
  86. chainManager: chainManager,
  87. blockPool: blockPool,
  88. rw: rw,
  89. peer: peer,
  90. id: fmt.Sprintf("%x", id[:8]),
  91. }
  92. err = self.handleStatus()
  93. if err == nil {
  94. self.propagateTxs()
  95. for {
  96. err = self.handle()
  97. if err != nil {
  98. self.blockPool.RemovePeer(self.id)
  99. break
  100. }
  101. }
  102. }
  103. return
  104. }
  105. func (self *ethProtocol) handle() error {
  106. msg, err := self.rw.ReadMsg()
  107. if err != nil {
  108. return err
  109. }
  110. if msg.Size > ProtocolMaxMsgSize {
  111. return self.protoError(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  112. }
  113. // make sure that the payload has been fully consumed
  114. defer msg.Discard()
  115. switch msg.Code {
  116. case GetTxMsg: // ignore
  117. case StatusMsg:
  118. return self.protoError(ErrExtraStatusMsg, "")
  119. case TxMsg:
  120. // TODO: rework using lazy RLP stream
  121. var txs []*types.Transaction
  122. if err := msg.Decode(&txs); err != nil {
  123. return self.protoError(ErrDecode, "msg %v: %v", msg, err)
  124. }
  125. for _, tx := range txs {
  126. jsonlogger.LogJson(&logger.EthTxReceived{
  127. TxHash: ethutil.Bytes2Hex(tx.Hash()),
  128. RemoteId: self.peer.ID().String(),
  129. })
  130. }
  131. self.txPool.AddTransactions(txs)
  132. case GetBlockHashesMsg:
  133. var request getBlockHashesMsgData
  134. if err := msg.Decode(&request); err != nil {
  135. return self.protoError(ErrDecode, "->msg %v: %v", msg, err)
  136. }
  137. //request.Amount = uint64(math.Min(float64(maxHashes), float64(request.Amount)))
  138. if request.Amount > maxHashes {
  139. request.Amount = maxHashes
  140. }
  141. hashes := self.chainManager.GetBlockHashesFromHash(request.Hash, request.Amount)
  142. return p2p.EncodeMsg(self.rw, BlockHashesMsg, ethutil.ByteSliceToInterface(hashes)...)
  143. case BlockHashesMsg:
  144. // TODO: redo using lazy decode , this way very inefficient on known chains
  145. msgStream := rlp.NewStream(msg.Payload)
  146. var err error
  147. var i int
  148. iter := func() (hash []byte, ok bool) {
  149. hash, err = msgStream.Bytes()
  150. if err == nil {
  151. i++
  152. ok = true
  153. } else {
  154. if err != io.EOF {
  155. self.protoError(ErrDecode, "msg %v: after %v hashes : %v", msg, i, err)
  156. }
  157. }
  158. return
  159. }
  160. self.blockPool.AddBlockHashes(iter, self.id)
  161. case GetBlocksMsg:
  162. msgStream := rlp.NewStream(msg.Payload)
  163. var blocks []interface{}
  164. var i int
  165. for {
  166. i++
  167. var hash []byte
  168. if err := msgStream.Decode(&hash); err != nil {
  169. if err == io.EOF {
  170. break
  171. } else {
  172. return self.protoError(ErrDecode, "msg %v: %v", msg, err)
  173. }
  174. }
  175. block := self.chainManager.GetBlock(hash)
  176. if block != nil {
  177. blocks = append(blocks, block)
  178. }
  179. if i == blockHashesBatchSize {
  180. break
  181. }
  182. }
  183. return p2p.EncodeMsg(self.rw, BlocksMsg, blocks...)
  184. case BlocksMsg:
  185. msgStream := rlp.NewStream(msg.Payload)
  186. for {
  187. var block types.Block
  188. if err := msgStream.Decode(&block); err != nil {
  189. if err == io.EOF {
  190. break
  191. } else {
  192. return self.protoError(ErrDecode, "msg %v: %v", msg, err)
  193. }
  194. }
  195. self.blockPool.AddBlock(&block, self.id)
  196. }
  197. case NewBlockMsg:
  198. var request newBlockMsgData
  199. if err := msg.Decode(&request); err != nil {
  200. return self.protoError(ErrDecode, "msg %v: %v", msg, err)
  201. }
  202. hash := request.Block.Hash()
  203. _, chainHead, _ := self.chainManager.Status()
  204. jsonlogger.LogJson(&logger.EthChainReceivedNewBlock{
  205. BlockHash: ethutil.Bytes2Hex(hash),
  206. BlockNumber: request.Block.Number(), // this surely must be zero
  207. ChainHeadHash: ethutil.Bytes2Hex(chainHead),
  208. BlockPrevHash: ethutil.Bytes2Hex(request.Block.ParentHash()),
  209. RemoteId: self.peer.ID().String(),
  210. })
  211. // to simplify backend interface adding a new block
  212. // uses AddPeer followed by AddHashes, AddBlock only if peer is the best peer
  213. // (or selected as new best peer)
  214. if self.blockPool.AddPeer(request.TD, hash, self.id, self.requestBlockHashes, self.requestBlocks, self.protoErrorDisconnect) {
  215. self.blockPool.AddBlock(request.Block, self.id)
  216. }
  217. default:
  218. return self.protoError(ErrInvalidMsgCode, "%v", msg.Code)
  219. }
  220. return nil
  221. }
  222. type statusMsgData struct {
  223. ProtocolVersion uint32
  224. NetworkId uint32
  225. TD *big.Int
  226. CurrentBlock []byte
  227. GenesisBlock []byte
  228. }
  229. func (self *ethProtocol) statusMsg() p2p.Msg {
  230. td, currentBlock, genesisBlock := self.chainManager.Status()
  231. return p2p.NewMsg(StatusMsg,
  232. uint32(ProtocolVersion),
  233. uint32(NetworkId),
  234. td,
  235. currentBlock,
  236. genesisBlock,
  237. )
  238. }
  239. func (self *ethProtocol) handleStatus() error {
  240. // send precanned status message
  241. if err := self.rw.WriteMsg(self.statusMsg()); err != nil {
  242. return err
  243. }
  244. // read and handle remote status
  245. msg, err := self.rw.ReadMsg()
  246. if err != nil {
  247. return err
  248. }
  249. if msg.Code != StatusMsg {
  250. return self.protoError(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Code, StatusMsg)
  251. }
  252. if msg.Size > ProtocolMaxMsgSize {
  253. return self.protoError(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  254. }
  255. var status statusMsgData
  256. if err := msg.Decode(&status); err != nil {
  257. return self.protoError(ErrDecode, "msg %v: %v", msg, err)
  258. }
  259. _, _, genesisBlock := self.chainManager.Status()
  260. if bytes.Compare(status.GenesisBlock, genesisBlock) != 0 {
  261. return self.protoError(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock, genesisBlock)
  262. }
  263. if status.NetworkId != NetworkId {
  264. return self.protoError(ErrNetworkIdMismatch, "%d (!= %d)", status.NetworkId, NetworkId)
  265. }
  266. if ProtocolVersion != status.ProtocolVersion {
  267. return self.protoError(ErrProtocolVersionMismatch, "%d (!= %d)", status.ProtocolVersion, ProtocolVersion)
  268. }
  269. self.peer.Infof("Peer is [eth] capable (%d/%d). TD=%v H=%x\n", status.ProtocolVersion, status.NetworkId, status.TD, status.CurrentBlock[:4])
  270. self.blockPool.AddPeer(status.TD, status.CurrentBlock, self.id, self.requestBlockHashes, self.requestBlocks, self.protoErrorDisconnect)
  271. return nil
  272. }
  273. func (self *ethProtocol) requestBlockHashes(from []byte) error {
  274. self.peer.Debugf("fetching hashes (%d) %x...\n", blockHashesBatchSize, from[0:4])
  275. return p2p.EncodeMsg(self.rw, GetBlockHashesMsg, interface{}(from), uint64(blockHashesBatchSize))
  276. }
  277. func (self *ethProtocol) requestBlocks(hashes [][]byte) error {
  278. self.peer.Debugf("fetching %v blocks", len(hashes))
  279. return p2p.EncodeMsg(self.rw, GetBlocksMsg, ethutil.ByteSliceToInterface(hashes)...)
  280. }
  281. func (self *ethProtocol) protoError(code int, format string, params ...interface{}) (err *protocolError) {
  282. err = ProtocolError(code, format, params...)
  283. if err.Fatal() {
  284. self.peer.Errorln("err %v", err)
  285. // disconnect
  286. } else {
  287. self.peer.Debugf("fyi %v", err)
  288. }
  289. return
  290. }
  291. func (self *ethProtocol) protoErrorDisconnect(code int, format string, params ...interface{}) {
  292. err := ProtocolError(code, format, params...)
  293. if err.Fatal() {
  294. self.peer.Errorln("err %v", err)
  295. // disconnect
  296. } else {
  297. self.peer.Debugf("fyi %v", err)
  298. }
  299. }
  300. func (self *ethProtocol) propagateTxs() {
  301. transactions := self.txPool.GetTransactions()
  302. iface := make([]interface{}, len(transactions))
  303. for i, transaction := range transactions {
  304. iface[i] = transaction
  305. }
  306. self.rw.WriteMsg(p2p.NewMsg(TxMsg, iface...))
  307. }