javascript_runtime.go 6.1 KB

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