-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathslow_solve.js
60 lines (47 loc) · 1.53 KB
/
slow_solve.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/* This file is part of the pastechan project.
* https://github.com/mvasilkov/pastechan
* Copyright (c) 2018 Mark Vasilkov (https://github.com/mvasilkov)
* License: MIT */
'use strict'
const assert = require('assert')
const crypto = require('crypto')
assert(crypto.getHashes().includes('blake2b512'))
const NONCE_CARDINALITY = 0x20000000000000
const dwordLo = a => a & 0xffffffff
const dwordHi = a => (a / 0x100000000) & 0xffffffff
function solve(salt, bits, contents, done) {
const bufNonce = Buffer.allocUnsafe(8)
const bufSep = Buffer.from('\t', 'utf8')
const bufSalt = Buffer.from(salt, 'hex')
const bufBits = Buffer.allocUnsafe(1)
bufBits.writeUInt8(bits, 0)
for (let n = 0; n < NONCE_CARDINALITY; ++n) {
bufNonce.writeUInt32LE(dwordLo(n), 0)
bufNonce.writeUInt32LE(dwordHi(n), 4)
let h = crypto.createHash('blake2b512')
h.update(bufNonce)
h.update(bufSep)
h.update(bufSalt)
h.update(bufSep)
h.update(bufBits)
h.update(bufSep)
h.update(contents, 'utf8')
h = h.digest()
let count = 0
for (let p = 0; p < 64; p += 4) {
const a = h.readUInt32LE(p)
if (a) {
count += 32 - Math.floor(Math.log2(a) + 1)
break
}
count += 32
}
if (count >= bits) {
done(n)
return
}
}
done(NONCE_CARDINALITY)
}
exports.solve = (salt, bits, contents) =>
new Promise(done => solve(salt, bits, contents, done))