Skip to content

Commit

Permalink
eth/tracers: optimize goja buffer conversion (ethereum#25156)
Browse files Browse the repository at this point in the history
This changes the []byte <-> Uint8Array conversion to use an
ArrayBuffer, avoiding inefficient copying of the slice data in Goja.

Co-authored-by: Felix Lange <fjl@twurst.com>
  • Loading branch information
2 people authored and maoueh committed Nov 29, 2022
1 parent 723cb19 commit 9bb31e5
Showing 1 changed file with 4 additions and 10 deletions.
14 changes: 4 additions & 10 deletions eth/tracers/js/goja.go
Expand Up @@ -54,11 +54,7 @@ type fromBufFn = func(vm *goja.Runtime, buf goja.Value, allowString bool) ([]byt

func toBuf(vm *goja.Runtime, bufType goja.Value, val []byte) (goja.Value, error) {
// bufType is usually Uint8Array. This is equivalent to `new Uint8Array(val)` in JS.
res, err := vm.New(bufType, vm.ToValue(val))
if err != nil {
return nil, err
}
return vm.ToValue(res), nil
return vm.New(bufType, vm.ToValue(vm.NewArrayBuffer(val)))
}

func fromBuf(vm *goja.Runtime, bufType goja.Value, buf goja.Value, allowString bool) ([]byte, error) {
Expand All @@ -69,6 +65,7 @@ func fromBuf(vm *goja.Runtime, bufType goja.Value, buf goja.Value, allowString b
break
}
return common.FromHex(obj.String()), nil

case "Array":
var b []byte
if err := vm.ExportTo(buf, &b); err != nil {
Expand All @@ -80,10 +77,7 @@ func fromBuf(vm *goja.Runtime, bufType goja.Value, buf goja.Value, allowString b
if !obj.Get("constructor").SameAs(bufType) {
break
}
var b []byte
if err := vm.ExportTo(buf, &b); err != nil {
return nil, err
}
b := obj.Get("buffer").Export().(goja.ArrayBuffer).Bytes()
return b, nil
}
return nil, fmt.Errorf("invalid buffer type")
Expand Down Expand Up @@ -775,7 +769,7 @@ func (co *contractObj) GetValue() goja.Value {
}

func (co *contractObj) GetInput() goja.Value {
input := co.contract.Input
input := common.CopyBytes(co.contract.Input)
res, err := co.toBuf(co.vm, input)
if err != nil {
co.vm.Interrupt(err)
Expand Down

0 comments on commit 9bb31e5

Please sign in to comment.