Skip to content

Instantly share code, notes, and snippets.

@zicklag
Created August 28, 2024 19:20
Show Gist options
  • Save zicklag/0b6f52be7f50762618abbebb96bd732b to your computer and use it in GitHub Desktop.
Save zicklag/0b6f52be7f50762618abbebb96bd732b to your computer and use it in GitHub Desktop.
Custom, dumb, simple pow in the browser.
export const computePow = async (
data: Uint8Array,
zero_prefix_length = 1
): Promise<ArrayBuffer> => {
const salted = new Uint8Array(data.length + 16);
for (let j = 0; j < data.length; j++) {
salted[j] = data[j];
}
const salt = new Uint8Array(salted.buffer, data.length);
crypto.getRandomValues(salt);
let i = 0;
const calcDigest = async (data: Uint8Array) => {
return new Uint8Array(await crypto.subtle.digest('SHA-256', data)).slice(0, zero_prefix_length);
};
let digest = await calcDigest(salted);
while (!digest.every((x) => x == 1)) {
if (i++ > 999999) throw 'Failed to find answer to proof-of-work in 999999 iterations.';
crypto.getRandomValues(salt);
digest = await calcDigest(salted);
}
return salt;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment