protocol.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // Copyright 2016 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 les
  17. import (
  18. "crypto/ecdsa"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "math/big"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. lpc "github.com/ethereum/go-ethereum/les/lespay/client"
  26. "github.com/ethereum/go-ethereum/p2p/enode"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. )
  29. // Constants to match up protocol versions and messages
  30. const (
  31. lpv2 = 2
  32. lpv3 = 3
  33. lpv4 = 4
  34. )
  35. // Supported versions of the les protocol (first is primary)
  36. var (
  37. ClientProtocolVersions = []uint{lpv2, lpv3}
  38. ServerProtocolVersions = []uint{lpv2, lpv3}
  39. AdvertiseProtocolVersions = []uint{lpv2} // clients are searching for the first advertised protocol in the list
  40. )
  41. // Number of implemented message corresponding to different protocol versions.
  42. var ProtocolLengths = map[uint]uint64{lpv2: 22, lpv3: 24, lpv4: 24}
  43. const (
  44. NetworkId = 1
  45. ProtocolMaxMsgSize = 10 * 1024 * 1024 // Maximum cap on the size of a protocol message
  46. )
  47. // les protocol message codes
  48. const (
  49. // Protocol messages inherited from LPV1
  50. StatusMsg = 0x00
  51. AnnounceMsg = 0x01
  52. GetBlockHeadersMsg = 0x02
  53. BlockHeadersMsg = 0x03
  54. GetBlockBodiesMsg = 0x04
  55. BlockBodiesMsg = 0x05
  56. GetReceiptsMsg = 0x06
  57. ReceiptsMsg = 0x07
  58. GetCodeMsg = 0x0a
  59. CodeMsg = 0x0b
  60. // Protocol messages introduced in LPV2
  61. GetProofsV2Msg = 0x0f
  62. ProofsV2Msg = 0x10
  63. GetHelperTrieProofsMsg = 0x11
  64. HelperTrieProofsMsg = 0x12
  65. SendTxV2Msg = 0x13
  66. GetTxStatusMsg = 0x14
  67. TxStatusMsg = 0x15
  68. // Protocol messages introduced in LPV3
  69. StopMsg = 0x16
  70. ResumeMsg = 0x17
  71. )
  72. type requestInfo struct {
  73. name string
  74. maxCount uint64
  75. refBasketFirst, refBasketRest float64
  76. }
  77. // reqMapping maps an LES request to one or two lespay service vector entries.
  78. // If rest != -1 and the request type is used with amounts larger than one then the
  79. // first one of the multi-request is mapped to first while the rest is mapped to rest.
  80. type reqMapping struct {
  81. first, rest int
  82. }
  83. var (
  84. // requests describes the available LES request types and their initializing amounts
  85. // in the lespay/client.ValueTracker reference basket. Initial values are estimates
  86. // based on the same values as the server's default cost estimates (reqAvgTimeCost).
  87. requests = map[uint64]requestInfo{
  88. GetBlockHeadersMsg: {"GetBlockHeaders", MaxHeaderFetch, 10, 1000},
  89. GetBlockBodiesMsg: {"GetBlockBodies", MaxBodyFetch, 1, 0},
  90. GetReceiptsMsg: {"GetReceipts", MaxReceiptFetch, 1, 0},
  91. GetCodeMsg: {"GetCode", MaxCodeFetch, 1, 0},
  92. GetProofsV2Msg: {"GetProofsV2", MaxProofsFetch, 10, 0},
  93. GetHelperTrieProofsMsg: {"GetHelperTrieProofs", MaxHelperTrieProofsFetch, 10, 100},
  94. SendTxV2Msg: {"SendTxV2", MaxTxSend, 1, 0},
  95. GetTxStatusMsg: {"GetTxStatus", MaxTxStatus, 10, 0},
  96. }
  97. requestList []lpc.RequestInfo
  98. requestMapping map[uint32]reqMapping
  99. )
  100. // init creates a request list and mapping between protocol message codes and lespay
  101. // service vector indices.
  102. func init() {
  103. requestMapping = make(map[uint32]reqMapping)
  104. for code, req := range requests {
  105. cost := reqAvgTimeCost[code]
  106. rm := reqMapping{len(requestList), -1}
  107. requestList = append(requestList, lpc.RequestInfo{
  108. Name: req.name + ".first",
  109. InitAmount: req.refBasketFirst,
  110. InitValue: float64(cost.baseCost + cost.reqCost),
  111. })
  112. if req.refBasketRest != 0 {
  113. rm.rest = len(requestList)
  114. requestList = append(requestList, lpc.RequestInfo{
  115. Name: req.name + ".rest",
  116. InitAmount: req.refBasketRest,
  117. InitValue: float64(cost.reqCost),
  118. })
  119. }
  120. requestMapping[uint32(code)] = rm
  121. }
  122. }
  123. type errCode int
  124. const (
  125. ErrMsgTooLarge = iota
  126. ErrDecode
  127. ErrInvalidMsgCode
  128. ErrProtocolVersionMismatch
  129. ErrNetworkIdMismatch
  130. ErrGenesisBlockMismatch
  131. ErrNoStatusMsg
  132. ErrExtraStatusMsg
  133. ErrSuspendedPeer
  134. ErrUselessPeer
  135. ErrRequestRejected
  136. ErrUnexpectedResponse
  137. ErrInvalidResponse
  138. ErrTooManyTimeouts
  139. ErrMissingKey
  140. ErrForkIDRejected
  141. )
  142. func (e errCode) String() string {
  143. return errorToString[int(e)]
  144. }
  145. // XXX change once legacy code is out
  146. var errorToString = map[int]string{
  147. ErrMsgTooLarge: "Message too long",
  148. ErrDecode: "Invalid message",
  149. ErrInvalidMsgCode: "Invalid message code",
  150. ErrProtocolVersionMismatch: "Protocol version mismatch",
  151. ErrNetworkIdMismatch: "NetworkId mismatch",
  152. ErrGenesisBlockMismatch: "Genesis block mismatch",
  153. ErrNoStatusMsg: "No status message",
  154. ErrExtraStatusMsg: "Extra status message",
  155. ErrSuspendedPeer: "Suspended peer",
  156. ErrRequestRejected: "Request rejected",
  157. ErrUnexpectedResponse: "Unexpected response",
  158. ErrInvalidResponse: "Invalid response",
  159. ErrTooManyTimeouts: "Too many request timeouts",
  160. ErrMissingKey: "Key missing from list",
  161. ErrForkIDRejected: "ForkID rejected",
  162. }
  163. // announceData is the network packet for the block announcements.
  164. type announceData struct {
  165. Hash common.Hash // Hash of one particular block being announced
  166. Number uint64 // Number of one particular block being announced
  167. Td *big.Int // Total difficulty of one particular block being announced
  168. ReorgDepth uint64
  169. Update keyValueList
  170. }
  171. // sanityCheck verifies that the values are reasonable, as a DoS protection
  172. func (a *announceData) sanityCheck() error {
  173. if tdlen := a.Td.BitLen(); tdlen > 100 {
  174. return fmt.Errorf("too large block TD: bitlen %d", tdlen)
  175. }
  176. return nil
  177. }
  178. // sign adds a signature to the block announcement by the given privKey
  179. func (a *announceData) sign(privKey *ecdsa.PrivateKey) {
  180. rlp, _ := rlp.EncodeToBytes(blockInfo{a.Hash, a.Number, a.Td})
  181. sig, _ := crypto.Sign(crypto.Keccak256(rlp), privKey)
  182. a.Update = a.Update.add("sign", sig)
  183. }
  184. // checkSignature verifies if the block announcement has a valid signature by the given pubKey
  185. func (a *announceData) checkSignature(id enode.ID, update keyValueMap) error {
  186. var sig []byte
  187. if err := update.get("sign", &sig); err != nil {
  188. return err
  189. }
  190. rlp, _ := rlp.EncodeToBytes(blockInfo{a.Hash, a.Number, a.Td})
  191. recPubkey, err := crypto.SigToPub(crypto.Keccak256(rlp), sig)
  192. if err != nil {
  193. return err
  194. }
  195. if id == enode.PubkeyToIDV4(recPubkey) {
  196. return nil
  197. }
  198. return errors.New("wrong signature")
  199. }
  200. type blockInfo struct {
  201. Hash common.Hash // Hash of one particular block being announced
  202. Number uint64 // Number of one particular block being announced
  203. Td *big.Int // Total difficulty of one particular block being announced
  204. }
  205. // getBlockHeadersData represents a block header query.
  206. type getBlockHeadersData struct {
  207. Origin hashOrNumber // Block from which to retrieve headers
  208. Amount uint64 // Maximum number of headers to retrieve
  209. Skip uint64 // Blocks to skip between consecutive headers
  210. Reverse bool // Query direction (false = rising towards latest, true = falling towards genesis)
  211. }
  212. // hashOrNumber is a combined field for specifying an origin block.
  213. type hashOrNumber struct {
  214. Hash common.Hash // Block hash from which to retrieve headers (excludes Number)
  215. Number uint64 // Block hash from which to retrieve headers (excludes Hash)
  216. }
  217. // EncodeRLP is a specialized encoder for hashOrNumber to encode only one of the
  218. // two contained union fields.
  219. func (hn *hashOrNumber) EncodeRLP(w io.Writer) error {
  220. if hn.Hash == (common.Hash{}) {
  221. return rlp.Encode(w, hn.Number)
  222. }
  223. if hn.Number != 0 {
  224. return fmt.Errorf("both origin hash (%x) and number (%d) provided", hn.Hash, hn.Number)
  225. }
  226. return rlp.Encode(w, hn.Hash)
  227. }
  228. // DecodeRLP is a specialized decoder for hashOrNumber to decode the contents
  229. // into either a block hash or a block number.
  230. func (hn *hashOrNumber) DecodeRLP(s *rlp.Stream) error {
  231. _, size, _ := s.Kind()
  232. origin, err := s.Raw()
  233. if err == nil {
  234. switch {
  235. case size == 32:
  236. err = rlp.DecodeBytes(origin, &hn.Hash)
  237. case size <= 8:
  238. err = rlp.DecodeBytes(origin, &hn.Number)
  239. default:
  240. err = fmt.Errorf("invalid input size %d for origin", size)
  241. }
  242. }
  243. return err
  244. }
  245. // CodeData is the network response packet for a node data retrieval.
  246. type CodeData []struct {
  247. Value []byte
  248. }