Created
March 14, 2019 02:26
-
-
Save TravisMullen/d542ddad929bf898f35433f582f40830 to your computer and use it in GitHub Desktop.
Unique Nonce Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { | |
randomFill | |
} = require('crypto') | |
const dirtyNonce = {} | |
const _nonce = () => { | |
const buf = Buffer.alloc(16) | |
return new Promise((resolve, reject) => { | |
randomFill(buf, (err, buf) => { | |
if (err) { reject(err) } | |
console.log(buf.toString('hex')) | |
resolve(buf) | |
}) | |
}) | |
} | |
const nonceGenerator = async () => { | |
console.time(`nonce generator`) | |
let nonce = await _nonce() | |
while (isDirty(nonce)) { | |
nonce = await _nonce() | |
} | |
console.timeEnd(`nonce generator`) | |
return nonce | |
} | |
const isDirty = nonce => { | |
const iv = nonce.toString('hex') | |
if (dirtyNonce[iv]) { | |
return true | |
} | |
dirtyNonce[iv] = true | |
return false | |
} | |
const isClean = nonce => !(isDirty(nonce)) | |
const dirty = () => ( | |
Object.keys(dirtyNonce) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment