protocol.go 8.6 KB

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