forked from 0chain/gosdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
3b1c83d
commit f97113e
Showing
7 changed files
with
254 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
//go:build js && wasm | ||
|
||
package jsbridge | ||
|
||
import ( | ||
"bytes" | ||
_ "embed" | ||
"fmt" | ||
"net/url" | ||
"os" | ||
"strings" | ||
"syscall/js" | ||
"text/template" | ||
) | ||
|
||
//go:embed zcnworker.js.tpl | ||
var WorkerJSTpl []byte | ||
|
||
func buildWorkerJS(args, env []string, path string) (string, error) { | ||
return buildJS(args, env, path, WorkerJSTpl) | ||
} | ||
|
||
func buildJS(args, env []string, path string, tpl []byte) (string, error) { | ||
var workerJS bytes.Buffer | ||
|
||
if len(args) == 0 { | ||
args = []string{path} | ||
} | ||
|
||
if len(env) == 0 { | ||
env = os.Environ() | ||
} | ||
|
||
if uRL, err := url.ParseRequestURI(path); err != nil || !uRL.IsAbs() { | ||
origin := js.Global().Get("location").Get("origin").String() | ||
baseURL, err := url.ParseRequestURI(origin) | ||
if err != nil { | ||
return "", err | ||
} | ||
path = baseURL.JoinPath(path).String() | ||
} | ||
|
||
data := templateData{ | ||
Path: path, | ||
Args: args, | ||
Env: env, | ||
} | ||
if err := template.Must(template.New("js").Parse(string(tpl))).Execute(&workerJS, data); err != nil { | ||
return "", err | ||
} | ||
return workerJS.String(), nil | ||
} | ||
|
||
type templateData struct { | ||
Path string | ||
Args []string | ||
Env []string | ||
} | ||
|
||
func (d templateData) ArgsToJS() string { | ||
el := []string{} | ||
for _, e := range d.Args { | ||
el = append(el, `"`+e+`"`) | ||
} | ||
return "[" + strings.Join(el, ",") + "]" | ||
} | ||
|
||
func (d templateData) EnvToJS() string { | ||
el := []string{} | ||
for _, entry := range d.Env { | ||
if k, v, ok := strings.Cut(entry, "="); ok { | ||
el = append(el, fmt.Sprintf(`"%s":"%s"`, k, v)) | ||
} | ||
} | ||
return "{" + strings.Join(el, ",") + "}" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
//go:build js && wasm | ||
// +build js,wasm | ||
|
||
package jsbridge | ||
|
||
import ( | ||
"context" | ||
|
||
"github.com/google/uuid" | ||
"github.com/hack-pad/go-webworkers/worker" | ||
"github.com/hack-pad/safejs" | ||
) | ||
|
||
type WasmWebWorker struct { | ||
// Name specifies an identifying name for the DedicatedWorkerGlobalScope representing the scope of the worker, which is mainly useful for debugging purposes. | ||
// If this is not specified, `Start` will create a UUIDv4 for it and populate back. | ||
Name string | ||
|
||
// Path is the path of the WASM to run as the Web Worker. | ||
// This can be a relative path on the server, or an abosolute URL. | ||
Path string | ||
|
||
// Args holds command line arguments, including the WASM as Args[0]. | ||
// If the Args field is empty or nil, Run uses {Path}. | ||
Args []string | ||
|
||
// Env specifies the environment of the process. | ||
// Each entry is of the form "key=value". | ||
// If Env is nil, the new Web Worker uses the current context's | ||
// environment. | ||
// If Env contains duplicate environment keys, only the last | ||
// value in the slice for each duplicate key is used. | ||
Env []string | ||
|
||
worker *worker.Worker | ||
} | ||
|
||
func NewWasmWebWorker(blobberURL, clientID, privateKey string) (*WasmWebWorker, error) { | ||
w := &WasmWebWorker{ | ||
Name: blobberURL, | ||
Env: []string{"BLOBBER_URL=" + blobberURL, "CLIENT_ID=" + clientID, "PRIVATE_KEY=" + privateKey, "MODE=worker"}, | ||
} | ||
|
||
if err := w.Start(); err != nil { | ||
return nil, err | ||
} | ||
return w, nil | ||
} | ||
|
||
func (ww *WasmWebWorker) Start() error { | ||
workerJS, err := buildWorkerJS(ww.Args, ww.Env, ww.Path) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
if ww.Name == "" { | ||
ww.Name = uuid.New().String() | ||
} | ||
|
||
wk, err := worker.NewFromScript(workerJS, worker.Options{Name: ww.Name}) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
ww.worker = wk | ||
|
||
return nil | ||
} | ||
|
||
// PostMessage sends data in a message to the worker, optionally transferring ownership of all items in transfers. | ||
func (ww *WasmWebWorker) PostMessage(data safejs.Value, transfers []safejs.Value) error { | ||
return ww.worker.PostMessage(data, transfers) | ||
} | ||
|
||
// Terminate immediately terminates the Worker. | ||
func (ww *WasmWebWorker) Terminate() { | ||
ww.worker.Terminate() | ||
} | ||
|
||
// Listen sends message events on a channel for events fired by self.postMessage() calls inside the Worker's global scope. | ||
// Stops the listener and closes the channel when ctx is canceled. | ||
func (ww *WasmWebWorker) Listen(ctx context.Context) (<-chan worker.MessageEvent, error) { | ||
return ww.worker.Listen(ctx) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
importScripts('https://cdn.jsdelivr.net/gh/golang/[email protected]/misc/wasm/wasm_exec.js'); | ||
importScripts('https://herumi.github.io/bls-wasm/browser/bls.js') | ||
|
||
const go = new Go(); | ||
go.argv = {{.ArgsToJS}} | ||
go.env = {{.EnvToJS}} | ||
const bls = self.bls | ||
bls.init(bls.BN254).then(()=>{}) | ||
WebAssembly.instantiateStreaming(fetch("http://localhost:8080/wasmsdk/demo/zcn.wasm"), go.importObject).then((result) => { | ||
go.run(result.instance); | ||
}); | ||
|
||
function hexStringToByte(str) { | ||
if (!str) return new Uint8Array() | ||
const a = [] | ||
for (let i = 0, len = str.length; i < len; i += 2) { | ||
a.push(parseInt(str.substr(i, 2), 16)) | ||
} | ||
|
||
return new Uint8Array(a) | ||
} | ||
|
||
self.__zcn_worker_wasm__ = { | ||
sign: async (hash, secretKey) => { | ||
if (!secretKey){ | ||
const errMsg = 'err: wasm blsSign function requires a secret key' | ||
console.warn(errMsg) | ||
throw new Error(errMsg) | ||
} | ||
const bytes = hexStringToByte(hash) | ||
const sk = bls.deserializeHexStrToSecretKey(secretKey) | ||
const sig = sk.sign(bytes) | ||
|
||
if (!sig) { | ||
const errMsg = 'err: wasm blsSign function failed to sign transaction' | ||
console.warn(errMsg) | ||
throw new Error(errMsg) | ||
} | ||
|
||
return sig.serializeToHexStr() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters