jsre.go 8.87 KB
Newer Older
1
// Copyright 2015 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
3
//
4
// The go-ethereum library is free software: you can redistribute it and/or modify
5 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
9
// The go-ethereum library is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 13 14
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
15
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16

17
// Package jsre provides execution environment for JavaScript.
zelig's avatar
zelig committed
18 19 20
package jsre

import (
21 22
	crand "crypto/rand"
	"encoding/binary"
zelig's avatar
zelig committed
23
	"fmt"
24
	"io"
zelig's avatar
zelig committed
25
	"io/ioutil"
26
	"math/rand"
27
	"time"
28

29
	"github.com/dop251/goja"
zelig's avatar
zelig committed
30
	"github.com/ethereum/go-ethereum/common"
zelig's avatar
zelig committed
31 32
)

33 34 35 36 37 38 39
// JSRE is a JS runtime environment embedding the goja interpreter.
// It provides helper functions to load code from files, run code snippets
// and bind native go objects to JS.
//
// The runtime runs all code on a dedicated event loop and does not expose the underlying
// goja runtime directly. To use the runtime, call JSRE.Do. When binding a Go function,
// use the Call type to gain access to the runtime.
zelig's avatar
zelig committed
40
type JSRE struct {
41
	assetPath     string
42
	output        io.Writer
43 44
	evalQueue     chan *evalReq
	stopEventLoop chan bool
45
	closed        chan struct{}
46 47 48 49 50 51 52
	vm            *goja.Runtime
}

// Call is the argument type of Go functions which are callable from JS.
type Call struct {
	goja.FunctionCall
	VM *goja.Runtime
53 54 55 56 57 58 59
}

// jsTimer is a single timer instance with a callback function
type jsTimer struct {
	timer    *time.Timer
	duration time.Duration
	interval bool
60
	call     goja.FunctionCall
zelig's avatar
zelig committed
61 62
}

63
// evalReq is a serialized vm execution request processed by runEventLoop.
64
type evalReq struct {
65
	fn   func(vm *goja.Runtime)
66 67 68 69
	done chan bool
}

// runtime must be stopped with Stop() after use and cannot be used after stopping
70
func New(assetPath string, output io.Writer) *JSRE {
zelig's avatar
zelig committed
71
	re := &JSRE{
72
		assetPath:     assetPath,
73
		output:        output,
74
		closed:        make(chan struct{}),
75 76
		evalQueue:     make(chan *evalReq),
		stopEventLoop: make(chan bool),
77
		vm:            goja.New(),
zelig's avatar
zelig committed
78
	}
79
	go re.runEventLoop()
80
	re.Set("loadScript", MakeCallback(re.vm, re.loadScript))
81
	re.Set("inspect", re.prettyPrintJS)
zelig's avatar
zelig committed
82 83 84
	return re
}

85 86 87 88 89 90 91 92 93 94 95 96
// randomSource returns a pseudo random value generator.
func randomSource() *rand.Rand {
	bytes := make([]byte, 8)
	seed := time.Now().UnixNano()
	if _, err := crand.Read(bytes); err == nil {
		seed = int64(binary.LittleEndian.Uint64(bytes))
	}

	src := rand.NewSource(seed)
	return rand.New(src)
}

97 98 99 100
// This function runs the main event loop from a goroutine that is started
// when JSRE is created. Use Stop() before exiting to properly stop it.
// The event loop processes vm access requests from the evalQueue in a
// serialized way and calls timer callback functions at the appropriate time.
101

102
// Exported functions always access the vm through the event queue. You can
103
// call the functions of the goja vm directly to circumvent the queue. These
104 105
// functions should be used if and only if running a routine that was already
// called from JS through an RPC call.
106 107
func (re *JSRE) runEventLoop() {
	defer close(re.closed)
108

109
	r := randomSource()
110
	re.vm.SetRandSource(r.Float64)
111

112 113 114
	registry := map[*jsTimer]*jsTimer{}
	ready := make(chan *jsTimer)

115 116
	newTimer := func(call goja.FunctionCall, interval bool) (*jsTimer, goja.Value) {
		delay := call.Argument(1).ToInteger()
117 118 119 120 121 122 123 124 125 126 127 128 129 130
		if 0 >= delay {
			delay = 1
		}
		timer := &jsTimer{
			duration: time.Duration(delay) * time.Millisecond,
			call:     call,
			interval: interval,
		}
		registry[timer] = timer

		timer.timer = time.AfterFunc(timer.duration, func() {
			ready <- timer
		})

131
		return timer, re.vm.ToValue(timer)
132 133
	}

134
	setTimeout := func(call goja.FunctionCall) goja.Value {
135 136 137 138
		_, value := newTimer(call, false)
		return value
	}

139
	setInterval := func(call goja.FunctionCall) goja.Value {
140 141 142 143
		_, value := newTimer(call, true)
		return value
	}

144 145
	clearTimeout := func(call goja.FunctionCall) goja.Value {
		timer := call.Argument(0).Export()
146 147 148 149
		if timer, ok := timer.(*jsTimer); ok {
			timer.timer.Stop()
			delete(registry, timer)
		}
150
		return goja.Undefined()
151
	}
152 153 154
	re.vm.Set("_setTimeout", setTimeout)
	re.vm.Set("_setInterval", setInterval)
	re.vm.RunString(`var setTimeout = function(args) {
155 156 157 158 159
		if (arguments.length < 1) {
			throw TypeError("Failed to execute 'setTimeout': 1 argument required, but only 0 present.");
		}
		return _setTimeout.apply(this, arguments);
	}`)
160
	re.vm.RunString(`var setInterval = function(args) {
161 162 163 164 165
		if (arguments.length < 1) {
			throw TypeError("Failed to execute 'setInterval': 1 argument required, but only 0 present.");
		}
		return _setInterval.apply(this, arguments);
	}`)
166 167
	re.vm.Set("clearTimeout", clearTimeout)
	re.vm.Set("clearInterval", clearTimeout)
168 169 170 171 172 173 174 175 176

	var waitForCallbacks bool

loop:
	for {
		select {
		case timer := <-ready:
			// execute callback, remove/reschedule the timer
			var arguments []interface{}
177 178
			if len(timer.call.Arguments) > 2 {
				tmp := timer.call.Arguments[2:]
179 180 181 182 183 184 185
				arguments = make([]interface{}, 2+len(tmp))
				for i, value := range tmp {
					arguments[i+2] = value
				}
			} else {
				arguments = make([]interface{}, 1)
			}
186 187 188 189
			arguments[0] = timer.call.Arguments[0]
			call, isFunc := goja.AssertFunction(timer.call.Arguments[0])
			if !isFunc {
				panic(re.vm.ToValue("js error: timer/timeout callback is not a function"))
190
			}
191
			call(goja.Null(), timer.call.Arguments...)
192

193 194
			_, inreg := registry[timer] // when clearInterval is called from within the callback don't reset it
			if timer.interval && inreg {
195 196 197 198 199 200 201
				timer.timer.Reset(timer.duration)
			} else {
				delete(registry, timer)
				if waitForCallbacks && (len(registry) == 0) {
					break loop
				}
			}
202
		case req := <-re.evalQueue:
203
			// run the code, send the result back
204
			req.fn(re.vm)
205
			close(req.done)
206 207 208
			if waitForCallbacks && (len(registry) == 0) {
				break loop
			}
209
		case waitForCallbacks = <-re.stopEventLoop:
210 211 212 213 214 215 216 217 218 219 220 221
			if !waitForCallbacks || (len(registry) == 0) {
				break loop
			}
		}
	}

	for _, timer := range registry {
		timer.timer.Stop()
		delete(registry, timer)
	}
}

Felix Lange's avatar
Felix Lange committed
222
// Do executes the given function on the JS event loop.
223
func (re *JSRE) Do(fn func(*goja.Runtime)) {
224 225
	done := make(chan bool)
	req := &evalReq{fn, done}
226
	re.evalQueue <- req
227 228 229
	<-done
}

230
// stops the event loop before exit, optionally waits for all timers to expire
231
func (re *JSRE) Stop(waitForCallbacks bool) {
232
	select {
233 234 235
	case <-re.closed:
	case re.stopEventLoop <- waitForCallbacks:
		<-re.closed
236
	}
237 238
}

zelig's avatar
zelig committed
239 240
// Exec(file) loads and runs the contents of a file
// if a relative path is given, the jsre's assetPath is used
241 242
func (re *JSRE) Exec(file string) error {
	code, err := ioutil.ReadFile(common.AbsolutePath(re.assetPath, file))
zelig's avatar
zelig committed
243 244 245
	if err != nil {
		return err
	}
246
	return re.Compile(file, string(code))
zelig's avatar
zelig committed
247 248
}

249
// Run runs a piece of JS code.
250 251
func (re *JSRE) Run(code string) (v goja.Value, err error) {
	re.Do(func(vm *goja.Runtime) { v, err = vm.RunString(code) })
252
	return v, err
zelig's avatar
zelig committed
253 254
}

255
// Set assigns value v to a variable in the JS environment.
256
func (re *JSRE) Set(ns string, v interface{}) (err error) {
257
	re.Do(func(vm *goja.Runtime) { vm.Set(ns, v) })
258
	return err
zelig's avatar
zelig committed
259 260
}

261 262 263 264 265 266 267 268 269
// MakeCallback turns the given function into a function that's callable by JS.
func MakeCallback(vm *goja.Runtime, fn func(Call) (goja.Value, error)) goja.Value {
	return vm.ToValue(func(call goja.FunctionCall) goja.Value {
		result, err := fn(Call{call, vm})
		if err != nil {
			panic(vm.NewGoError(err))
		}
		return result
	})
zelig's avatar
zelig committed
270 271
}

272 273 274 275
// Evaluate executes code and pretty prints the result to the specified output stream.
func (re *JSRE) Evaluate(code string, w io.Writer) {
	re.Do(func(vm *goja.Runtime) {
		val, err := vm.RunString(code)
276
		if err != nil {
277
			prettyError(vm, err, w)
278 279
		} else {
			prettyPrint(vm, val, w)
280
		}
281
		fmt.Fprintln(w)
282
	})
zelig's avatar
zelig committed
283
}
284

285
// Compile compiles and then runs a piece of JS code.
286 287
func (re *JSRE) Compile(filename string, src string) (err error) {
	re.Do(func(vm *goja.Runtime) { _, err = compileAndRun(vm, filename, src) })
288 289 290
	return err
}

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
// loadScript loads and executes a JS file.
func (re *JSRE) loadScript(call Call) (goja.Value, error) {
	file := call.Argument(0).ToString().String()
	file = common.AbsolutePath(re.assetPath, file)
	source, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, fmt.Errorf("Could not read file %s: %v", file, err)
	}
	value, err := compileAndRun(re.vm, file, string(source))
	if err != nil {
		return nil, fmt.Errorf("Error while compiling or running script: %v", err)
	}
	return value, nil
}

func compileAndRun(vm *goja.Runtime, filename string, src string) (goja.Value, error) {
	script, err := goja.Compile(filename, src, false)
308
	if err != nil {
309
		return goja.Null(), err
310
	}
311
	return vm.RunProgram(script)
312
}