Skip to content

Commit

Permalink
initial webassembly demo
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasmenendez committed Apr 4, 2024
1 parent c0e333b commit 7cd17a8
Show file tree
Hide file tree
Showing 2 changed files with 102 additions and 0 deletions.
72 changes: 72 additions & 0 deletions cmd/webassembly/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
//go:build js && wasm
// +build js,wasm

package main

import (
"encoding/json"
"fmt"
"syscall/js"

"github.com/lucasmenendez/gosss"
)

const (
// js names
jsClassName = "GoSSS"
jsHideMethod = "hide"
jsRecoverMethod = "recover"
// required number of arguments for each method
hidedNArgs = 3 // msg, nshares, minshares
recoverdNArgs = 1 // shares
)

func wasmError(err error) js.Value {
return js.Global().Call("throwError", js.ValueOf(err.Error()))
}

func main() {
gosssClass := js.ValueOf(map[string]interface{}{})
gosssClass.Set(jsHideMethod, js.FuncOf(func(this js.Value, p []js.Value) interface{} {
if len(p) != hidedNArgs {
return wasmError(fmt.Errorf("invalid number of arguments"))
}
msg := p[0].String()
nshares := p[1].Int()
minshares := p[2].Int()
// hide the message
shares, err := gosss.HideMessage([]byte(msg), &gosss.Config{
Shares: nshares,
Min: minshares,
})
if err != nil {
return wasmError(err)
}
jsonShares, err := json.Marshal(shares)
if err != nil {
return wasmError(err)
}
return string(jsonShares)
}))

gosssClass.Set(jsRecoverMethod, js.FuncOf(func(this js.Value, p []js.Value) interface{} {
if len(p) != recoverdNArgs {
return wasmError(fmt.Errorf("invalid number of arguments"))
}
// recover the shares from the json string
var shares []string
if err := json.Unmarshal([]byte(p[0].String()), &shares); err != nil {
return wasmError(err)
}
// recover the message
msg, err := gosss.RecoverMessage(shares, nil)
if err != nil {
return wasmError(err)
}
return string(msg)
}))

js.Global().Set(jsClassName, gosssClass)
// keep the program running forever
select {}
}
30 changes: 30 additions & 0 deletions web/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<html>
<head>
<title>Go Shamir Secret Sharing demo</title>
</head>
<body>
<script src="wasm_exec.js"></script>
<script>
function throwError(e) {
console.error(e);
}

function hide(message, sharesCount, threshold) {
let rawshares = GoSSS.hide(message, sharesCount, threshold);
return JSON.parse(rawshares);
}

function recover(shares) {
let message = GoSSS.recover(JSON.stringify(shares));
return message;
}

(async function() {
const go = new Go();
const result = await WebAssembly.instantiateStreaming(fetch("gosss.wasm"), go.importObject);
go.run(result.instance);
})()
</script>
</body>
</html>

0 comments on commit 7cd17a8

Please sign in to comment.