web3.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package api
  2. import (
  3. "github.com/ethereum/go-ethereum/common"
  4. "github.com/ethereum/go-ethereum/crypto"
  5. "github.com/ethereum/go-ethereum/rpc/codec"
  6. "github.com/ethereum/go-ethereum/rpc/shared"
  7. "github.com/ethereum/go-ethereum/xeth"
  8. )
  9. const (
  10. Web3ApiVersion = "1.0"
  11. )
  12. var (
  13. // mapping between methods and handlers
  14. Web3Mapping = map[string]web3handler{
  15. "web3_sha3": (*web3Api).Sha3,
  16. "web3_clientVersion": (*web3Api).ClientVersion,
  17. }
  18. )
  19. // web3 callback handler
  20. type web3handler func(*web3Api, *shared.Request) (interface{}, error)
  21. // web3 api provider
  22. type web3Api struct {
  23. xeth *xeth.XEth
  24. methods map[string]web3handler
  25. codec codec.ApiCoder
  26. }
  27. // create a new web3 api instance
  28. func NewWeb3Api(xeth *xeth.XEth, coder codec.Codec) *web3Api {
  29. return &web3Api{
  30. xeth: xeth,
  31. methods: Web3Mapping,
  32. codec: coder.New(nil),
  33. }
  34. }
  35. // collection with supported methods
  36. func (self *web3Api) Methods() []string {
  37. methods := make([]string, len(self.methods))
  38. i := 0
  39. for k := range self.methods {
  40. methods[i] = k
  41. i++
  42. }
  43. return methods
  44. }
  45. // Execute given request
  46. func (self *web3Api) Execute(req *shared.Request) (interface{}, error) {
  47. if callback, ok := self.methods[req.Method]; ok {
  48. return callback(self, req)
  49. }
  50. return nil, &shared.NotImplementedError{req.Method}
  51. }
  52. func (self *web3Api) Name() string {
  53. return shared.Web3ApiName
  54. }
  55. func (self *web3Api) ApiVersion() string {
  56. return Web3ApiVersion
  57. }
  58. // Calculates the sha3 over req.Params.Data
  59. func (self *web3Api) Sha3(req *shared.Request) (interface{}, error) {
  60. args := new(Sha3Args)
  61. if err := self.codec.Decode(req.Params, &args); err != nil {
  62. return nil, err
  63. }
  64. return common.ToHex(crypto.Sha3(common.FromHex(args.Data))), nil
  65. }
  66. // returns the xeth client vrsion
  67. func (self *web3Api) ClientVersion(req *shared.Request) (interface{}, error) {
  68. return self.xeth.ClientVersion(), nil
  69. }