javascript_runtime.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. package javascript
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "path"
  7. "path/filepath"
  8. "github.com/ethereum/go-ethereum/cmd/utils"
  9. "github.com/ethereum/go-ethereum/core"
  10. "github.com/ethereum/go-ethereum/core/types"
  11. "github.com/ethereum/go-ethereum/eth"
  12. "github.com/ethereum/go-ethereum/ethutil"
  13. "github.com/ethereum/go-ethereum/event"
  14. "github.com/ethereum/go-ethereum/logger"
  15. "github.com/ethereum/go-ethereum/state"
  16. "github.com/ethereum/go-ethereum/xeth"
  17. "github.com/obscuren/otto"
  18. )
  19. var jsrelogger = logger.NewLogger("JSRE")
  20. type JSRE struct {
  21. ethereum *eth.Ethereum
  22. Vm *otto.Otto
  23. pipe *xeth.XEth
  24. events event.Subscription
  25. objectCb map[string][]otto.Value
  26. }
  27. func (jsre *JSRE) LoadExtFile(path string) {
  28. result, err := ioutil.ReadFile(path)
  29. if err == nil {
  30. jsre.Vm.Run(result)
  31. } else {
  32. jsrelogger.Infoln("Could not load file:", path)
  33. }
  34. }
  35. func (jsre *JSRE) LoadIntFile(file string) {
  36. assetPath := path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist", "assets", "ext")
  37. jsre.LoadExtFile(path.Join(assetPath, file))
  38. }
  39. func NewJSRE(ethereum *eth.Ethereum) *JSRE {
  40. re := &JSRE{
  41. ethereum,
  42. otto.New(),
  43. xeth.New(ethereum),
  44. nil,
  45. make(map[string][]otto.Value),
  46. }
  47. // Init the JS lib
  48. re.Vm.Run(jsLib)
  49. // Load extra javascript files
  50. re.LoadIntFile("bignumber.min.js")
  51. // Subscribe to events
  52. mux := ethereum.EventMux()
  53. re.events = mux.Subscribe(core.NewBlockEvent{})
  54. // We have to make sure that, whoever calls this, calls "Stop"
  55. go re.mainLoop()
  56. re.Bind("eth", &JSEthereum{re.pipe, re.Vm, ethereum})
  57. re.initStdFuncs()
  58. jsrelogger.Infoln("started")
  59. return re
  60. }
  61. func (self *JSRE) Bind(name string, v interface{}) {
  62. self.Vm.Set(name, v)
  63. }
  64. func (self *JSRE) Run(code string) (otto.Value, error) {
  65. return self.Vm.Run(code)
  66. }
  67. func (self *JSRE) Require(file string) error {
  68. if len(filepath.Ext(file)) == 0 {
  69. file += ".js"
  70. }
  71. fh, err := os.Open(file)
  72. if err != nil {
  73. return err
  74. }
  75. content, _ := ioutil.ReadAll(fh)
  76. self.Run("exports = {};(function() {" + string(content) + "})();")
  77. return nil
  78. }
  79. func (self *JSRE) Stop() {
  80. self.events.Unsubscribe()
  81. jsrelogger.Infoln("stopped")
  82. }
  83. func (self *JSRE) mainLoop() {
  84. for _ = range self.events.Chan() {
  85. }
  86. }
  87. func (self *JSRE) initStdFuncs() {
  88. t, _ := self.Vm.Get("eth")
  89. eth := t.Object()
  90. eth.Set("watch", self.watch)
  91. eth.Set("addPeer", self.addPeer)
  92. eth.Set("require", self.require)
  93. eth.Set("stopMining", self.stopMining)
  94. eth.Set("startMining", self.startMining)
  95. eth.Set("execBlock", self.execBlock)
  96. eth.Set("dump", self.dump)
  97. eth.Set("export", self.export)
  98. }
  99. /*
  100. * The following methods are natively implemented javascript functions
  101. */
  102. func (self *JSRE) dump(call otto.FunctionCall) otto.Value {
  103. var block *types.Block
  104. if len(call.ArgumentList) > 0 {
  105. if call.Argument(0).IsNumber() {
  106. num, _ := call.Argument(0).ToInteger()
  107. block = self.ethereum.ChainManager().GetBlockByNumber(uint64(num))
  108. } else if call.Argument(0).IsString() {
  109. hash, _ := call.Argument(0).ToString()
  110. block = self.ethereum.ChainManager().GetBlock(ethutil.Hex2Bytes(hash))
  111. } else {
  112. fmt.Println("invalid argument for dump. Either hex string or number")
  113. }
  114. if block == nil {
  115. fmt.Println("block not found")
  116. return otto.UndefinedValue()
  117. }
  118. } else {
  119. block = self.ethereum.ChainManager().CurrentBlock()
  120. }
  121. statedb := state.New(block.Root(), self.ethereum.Db())
  122. v, _ := self.Vm.ToValue(statedb.Dump())
  123. return v
  124. }
  125. func (self *JSRE) stopMining(call otto.FunctionCall) otto.Value {
  126. v, _ := self.Vm.ToValue(utils.StopMining(self.ethereum))
  127. return v
  128. }
  129. func (self *JSRE) startMining(call otto.FunctionCall) otto.Value {
  130. v, _ := self.Vm.ToValue(utils.StartMining(self.ethereum))
  131. return v
  132. }
  133. // eth.watch
  134. func (self *JSRE) watch(call otto.FunctionCall) otto.Value {
  135. addr, _ := call.Argument(0).ToString()
  136. var storageAddr string
  137. var cb otto.Value
  138. var storageCallback bool
  139. if len(call.ArgumentList) > 2 {
  140. storageCallback = true
  141. storageAddr, _ = call.Argument(1).ToString()
  142. cb = call.Argument(2)
  143. } else {
  144. cb = call.Argument(1)
  145. }
  146. if storageCallback {
  147. self.objectCb[addr+storageAddr] = append(self.objectCb[addr+storageAddr], cb)
  148. // event := "storage:" + string(ethutil.Hex2Bytes(addr)) + ":" + string(ethutil.Hex2Bytes(storageAddr))
  149. // self.ethereum.EventMux().Subscribe(event, self.changeChan)
  150. } else {
  151. self.objectCb[addr] = append(self.objectCb[addr], cb)
  152. // event := "object:" + string(ethutil.Hex2Bytes(addr))
  153. // self.ethereum.EventMux().Subscribe(event, self.changeChan)
  154. }
  155. return otto.UndefinedValue()
  156. }
  157. func (self *JSRE) addPeer(call otto.FunctionCall) otto.Value {
  158. nodeURL, err := call.Argument(0).ToString()
  159. if err != nil {
  160. return otto.FalseValue()
  161. }
  162. if err := self.ethereum.SuggestPeer(nodeURL); err != nil {
  163. return otto.FalseValue()
  164. }
  165. return otto.TrueValue()
  166. }
  167. func (self *JSRE) require(call otto.FunctionCall) otto.Value {
  168. file, err := call.Argument(0).ToString()
  169. if err != nil {
  170. return otto.UndefinedValue()
  171. }
  172. if err := self.Require(file); err != nil {
  173. fmt.Println("err:", err)
  174. return otto.UndefinedValue()
  175. }
  176. t, _ := self.Vm.Get("exports")
  177. return t
  178. }
  179. func (self *JSRE) execBlock(call otto.FunctionCall) otto.Value {
  180. hash, err := call.Argument(0).ToString()
  181. if err != nil {
  182. return otto.UndefinedValue()
  183. }
  184. err = utils.BlockDo(self.ethereum, ethutil.Hex2Bytes(hash))
  185. if err != nil {
  186. fmt.Println(err)
  187. return otto.FalseValue()
  188. }
  189. return otto.TrueValue()
  190. }
  191. func (self *JSRE) export(call otto.FunctionCall) otto.Value {
  192. fn, err := call.Argument(0).ToString()
  193. if err != nil {
  194. fmt.Println(err)
  195. return otto.FalseValue()
  196. }
  197. data := self.ethereum.ChainManager().Export()
  198. if err := ethutil.WriteFile(fn, data); err != nil {
  199. fmt.Println(err)
  200. return otto.FalseValue()
  201. }
  202. return otto.TrueValue()
  203. }