javascript_runtime.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package javascript
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "path"
  7. "path/filepath"
  8. "github.com/ethereum/go-ethereum/logger"
  9. "github.com/ethereum/go-ethereum/xeth"
  10. "github.com/obscuren/otto"
  11. )
  12. var jsrelogger = logger.NewLogger("JSRE")
  13. type JSRE struct {
  14. Vm *otto.Otto
  15. xeth *xeth.XEth
  16. objectCb map[string][]otto.Value
  17. }
  18. func (jsre *JSRE) LoadExtFile(path string) {
  19. result, err := ioutil.ReadFile(path)
  20. if err == nil {
  21. jsre.Vm.Run(result)
  22. } else {
  23. jsrelogger.Infoln("Could not load file:", path)
  24. }
  25. }
  26. func (jsre *JSRE) LoadIntFile(file string) {
  27. assetPath := path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist", "assets", "ext")
  28. jsre.LoadExtFile(path.Join(assetPath, file))
  29. }
  30. func NewJSRE(xeth *xeth.XEth) *JSRE {
  31. re := &JSRE{
  32. otto.New(),
  33. xeth,
  34. make(map[string][]otto.Value),
  35. }
  36. // Init the JS lib
  37. re.Vm.Run(jsLib)
  38. // Load extra javascript files
  39. re.LoadIntFile("bignumber.min.js")
  40. re.Bind("eth", &JSEthereum{re.xeth, re.Vm})
  41. re.initStdFuncs()
  42. jsrelogger.Infoln("started")
  43. return re
  44. }
  45. func (self *JSRE) Bind(name string, v interface{}) {
  46. self.Vm.Set(name, v)
  47. }
  48. func (self *JSRE) Run(code string) (otto.Value, error) {
  49. return self.Vm.Run(code)
  50. }
  51. func (self *JSRE) initStdFuncs() {
  52. t, _ := self.Vm.Get("eth")
  53. eth := t.Object()
  54. eth.Set("require", self.require)
  55. }
  56. func (self *JSRE) Require(file string) error {
  57. if len(filepath.Ext(file)) == 0 {
  58. file += ".js"
  59. }
  60. fh, err := os.Open(file)
  61. if err != nil {
  62. return err
  63. }
  64. content, _ := ioutil.ReadAll(fh)
  65. self.Run("exports = {};(function() {" + string(content) + "})();")
  66. return nil
  67. }
  68. func (self *JSRE) require(call otto.FunctionCall) otto.Value {
  69. file, err := call.Argument(0).ToString()
  70. if err != nil {
  71. return otto.UndefinedValue()
  72. }
  73. if err := self.Require(file); err != nil {
  74. fmt.Println("err:", err)
  75. return otto.UndefinedValue()
  76. }
  77. t, _ := self.Vm.Get("exports")
  78. return t
  79. }