Created
June 3, 2023 16:39
-
-
Save einsitang/7605abd76e1f723f7a0ea1ae4c3ca411 to your computer and use it in GitHub Desktop.
proof-of-work
This file contains 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
// 使用前先安装 md5 模块 : npm install md5 | |
const md5 = require("md5") | |
// 时间戳截取长度 , 从后向前截取 | |
const LENGTH = 6 | |
// check proof of work data | |
const checkPow = (randomTxt, timestamp) => { | |
let [numStr] = getTimeState(timestamp) | |
let randMd5Str = md5(randomTxt) | |
return randMd5Str.indexOf(numStr) != -1 | |
} | |
/** | |
* 获取 [截取字符串,时间戳] | |
* | |
* @param {long} fixedTimestamp 固定时间戳,可选,如果设置了则 numStr 以该时间戳截取 | |
* @returns [numStr,timestamp] | |
*/ | |
const getTimeState = (fixedTimestamp) => { | |
let timestamp = !!fixedTimestamp ? fixedTimestamp : new Date().getTime() | |
if(timestamp >>> 38 < 0){ | |
throw new Error(`${timestamp} is don't look like timestamp type`) | |
} | |
let timestampStr = timestamp.toString() | |
let cutTimestampStr = timestampStr.substr(-LENGTH) | |
let num = Number.parseInt(cutTimestampStr) | |
let numStr = num.toString(16) | |
return [numStr, timestamp] | |
} | |
/** | |
* generate proof of work data | |
*/ | |
const pow = () => { | |
let [numStr, timestamp] = getTimeState() | |
let md5Str = "" | |
let count = 0, maxCount = 2000 | |
let randomStr | |
while (md5Str.indexOf(numStr) == -1) { | |
randomStr = Math.random().toString(36).substr(3) | |
md5Str = md5(randomStr) | |
if (count++ > maxCount) { | |
[numStr, timestamp] = getTimeState() | |
count = 0 | |
} | |
} | |
return [randomStr, timestamp] | |
} | |
console.time('exhaustive') | |
let [randomStr, timestamp] = pow() | |
console.timeEnd('exhaustive') | |
console.log(`randomStr : ${randomStr} hash(randomStr)=> ${md5(randomStr)} , timestamp : ${timestamp} `) | |
console.time('check') | |
console.log(`pow checkout : ${checkPow(randomStr, timestamp)}`) | |
console.timeEnd('check') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment