Skip to content

Instantly share code, notes, and snippets.

@matheusfillipe
Last active April 26, 2022 23:49
Show Gist options
  • Save matheusfillipe/ba33af10b8d7df70f268879a54cf21d0 to your computer and use it in GitHub Desktop.
Save matheusfillipe/ba33af10b8d7df70f268879a54cf21d0 to your computer and use it in GitHub Desktop.
Simple proof of work concept using javascript
// Proof or work
const difficulty = 3
async function sha256(message) {
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
function convertBase(value, to_range) {
const from_base = 10;
const to_base = to_range.length;
var from_range = "0123456789";
var dec_value = value.toString().split('').reverse().reduce(function (carry, digit, index) {
if (from_range.indexOf(digit) === -1) throw new Error('Invalid digit `'+digit+'` for base '+from_base+'.');
return carry += from_range.indexOf(digit) * (Math.pow(from_base, index));
}, 0);
var new_value = '';
while (dec_value > 0) {
new_value = to_range[dec_value % to_base] + new_value;
dec_value = (dec_value - (dec_value % to_base)) / to_base;
}
return new_value || '0';
}
async function bruteforce(name) {
let salt = "";
// Loop through all possible words until sha256(name + salt) === hash000...
let symbols = []
for (let i = 32; i < 127; i++) {
symbols.push(String.fromCharCode(i))
}
let i = 0
while (true) {
salt = convertBase(i, symbols)
add = false;
i++;
const test = await sha256(name + salt);
if (test.endsWith("0".repeat(difficulty))) {
return salt;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment