Skip to content

Instantly share code, notes, and snippets.

@s1na
Created May 17, 2019 09:41
Show Gist options
  • Save s1na/92eae826c696de5e4d60708f8743e59f to your computer and use it in GitHub Desktop.
Save s1na/92eae826c696de5e4d60708f8743e59f to your computer and use it in GitHub Desktop.
keccak256 wasm
const fs = require('fs')
const path = require('path')
const memset = (mem, data, offset) => {
const asBytes = new Uint8Array(mem.buffer, offset, data.length)
asBytes.set(data)
}
const memget = (mem, offset, length) => {
return Buffer.from(new Uint8Array(mem.buffer, offset, length))
}
const wasmFile = fs.readFileSync(path.join(__dirname, 'keccak256_rhash.wasm'))
const mod = new WebAssembly.Module(wasmFile)
const instance = new WebAssembly.Instance(mod)
const mem = instance.exports.memory
const heapBase = instance.exports.__data_end
module.exports = (a) => {
data = a
// Zero out enough memory for input + output
memset(mem, Buffer.alloc(a.length + 32), heapBase)
// Write input to memory
memset(mem, a, heapBase)
try {
instance.exports._main(heapBase + a.length, heapBase, a.length)
} catch (e) {
// console.log(e)
}
return memget(mem, heapBase + a.length, 32)
}
@cdetrio
Copy link

cdetrio commented Jul 9, 2019

$ node --wasm-interpret-all --liftoff --no-wasm-tier-up sha3.js
start_keccak256: 0.376ms
result: <Buffer f1 88 5e da 54 b7 a0 53 31 8c d4 1e 20 93 22 0d ab 15 d6 53 81 b1 15 7a 36 33 a8 3b fd 5c 92 39>

$ md5 keccak256_rhash.wasm
MD5 (keccak256_rhash.wasm) = 28b206b953497614d5f10d6f77642c91
const fs = require('fs')
const path = require('path')

const memset = (mem, data, offset) => {
  const asBytes = new Uint8Array(mem.buffer, offset, data.length)
  asBytes.set(data)
}

const memget = (mem, offset, length) => {
  return Buffer.from(new Uint8Array(mem.buffer, offset, length))
}

const wasmFile = fs.readFileSync(path.join(__dirname, 'keccak256_rhash.wasm'))
const mod = new WebAssembly.Module(wasmFile)
const instance = new WebAssembly.Instance(mod, {})
const mem = instance.exports.memory
const heapBase = instance.exports.__data_end

function run(a) {
  data = a
  // Zero out enough memory for input + output
  memset(mem, Buffer.alloc(a.length + 32), heapBase)

  // Write input to memory
  memset(mem, a, heapBase)

  try {
    console.time("start_keccak256")
    instance.exports._main(heapBase + a.length, heapBase, a.length)
    console.timeEnd("start_keccak256")
  } catch (e) {
    // console.log(e)
  }

  return memget(mem, heapBase + a.length, 32)
}

let result = run(Buffer.from([1, 2, 3]));
console.log('result:', result);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment