util.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. This file is part of go-ethereum
  3. go-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. go-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. package rpc
  15. import (
  16. "encoding/json"
  17. "io"
  18. "net/http"
  19. "github.com/ethereum/go-ethereum/ethutil"
  20. "github.com/ethereum/go-ethereum/logger"
  21. "github.com/ethereum/go-ethereum/state"
  22. )
  23. var rpclogger = logger.NewLogger("RPC")
  24. type JsonWrapper struct{}
  25. func (self JsonWrapper) Send(writer io.Writer, v interface{}) (n int, err error) {
  26. var payload []byte
  27. payload, err = json.Marshal(v)
  28. if err != nil {
  29. rpclogger.Fatalln("Error marshalling JSON", err)
  30. return 0, err
  31. }
  32. rpclogger.DebugDetailf("Sending payload: %s", payload)
  33. return writer.Write(payload)
  34. }
  35. func (self JsonWrapper) ParseRequestBody(req *http.Request) (RpcRequest, error) {
  36. var reqParsed RpcRequest
  37. // Convert JSON to native types
  38. d := json.NewDecoder(req.Body)
  39. defer req.Body.Close()
  40. err := d.Decode(&reqParsed)
  41. if err != nil {
  42. rpclogger.Errorln("Error decoding JSON: ", err)
  43. return reqParsed, err
  44. }
  45. rpclogger.DebugDetailf("Parsed request: %s", reqParsed)
  46. return reqParsed, nil
  47. }
  48. func toHex(b []byte) string {
  49. return "0x" + ethutil.Bytes2Hex(b)
  50. }
  51. func fromHex(s string) []byte {
  52. if len(s) > 1 {
  53. if s[0:2] == "0x" {
  54. s = s[2:]
  55. }
  56. return ethutil.Hex2Bytes(s)
  57. }
  58. return nil
  59. }
  60. type RpcServer interface {
  61. Start()
  62. Stop()
  63. }
  64. type Log struct {
  65. Address string `json:"address"`
  66. Topics []string `json:"topics"`
  67. Data string `json:"data"`
  68. }
  69. func toLogs(logs state.Logs) (ls []Log) {
  70. ls = make([]Log, len(logs))
  71. for i, log := range logs {
  72. var l Log
  73. l.Topics = make([]string, len(log.Topics()))
  74. l.Address = toHex(log.Address())
  75. l.Data = toHex(log.Data())
  76. for j, topic := range log.Topics() {
  77. l.Topics[j] = toHex(topic)
  78. }
  79. ls[i] = l
  80. }
  81. return
  82. }