-
Notifications
You must be signed in to change notification settings - Fork 0
/
calcNonce.js
119 lines (98 loc) · 2.34 KB
/
calcNonce.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const fs = require('fs')
const CryptoJS = require("crypto-js")
let newHash_ = ""
let newNonce_ = ""
let runtime_ = ""
let leading_zero = ""
//! set digit here
let digit = 4
//!
// * 定義前導零的位數
function setDigit(num){
for (let i=0; i < num; i++){
leading_zero += "0"
}
}
//! set leading_zero
setDigit(digit)
//!
// * wordArray 轉成 string
function hashIt(str) {
let wordAry = CryptoJS.SHA256(str)
return CryptoJS.enc.Hex.stringify(wordAry)
}
// * 如果出來的 hash 不符合前導零規定,就 mine
function mine() {
let found = false
let t1 = Date.now()
for (var x = 0; !found; x++) {
// for (var x = 0; x <= 1000000 && !found; x++) {
let newStr = `${block}${x}${data}`
let newHash = hashIt(newStr)
if (newHash.substr(0, digit) === leading_zero) {
let t2 = Date.now()
let runtime = t2 - t1
found = true
newNonce_ = x
newHash_ = newHash
runtime_ = runtime
console.log(`
the valid nonce is : ${newNonce_}
newHash : ${newHash}
runtime : ${runtime} ms
`)
// break
}
if (x > Number.MAX_VALUE - 1 ){
console.log(`oh my God !! computer can't calculate the nonce... ...`);
}
}
}
let block = fs.readFileSync('./input/block.txt', 'utf8')
let nonce = fs.readFileSync('./input/nonce.txt', 'utf8')
let data = fs.readFileSync('./input/data.txt', 'utf8')
let string = `${block}${nonce}${data}`
let hash = hashIt(string)
let valid = hash.substr(0, digit) === leading_zero
// print info
console.log(`
============================
leading_zero: ${leading_zero}
============================
block: ${block}
nonce: ${nonce}
data:
>>|${data}
===> hash: ${hash}
============================
`);
//! check hash...
if (valid) {
console.log(`
Good !
The nonce is valid (leading_zero: '${leading_zero}'): ${nonce}
hash : ${hash}
`)
}
if (!valid){
console.log("mining... ");
mine()
let log = `
============================
leading_zero: ${leading_zero}
============================
block: ${block}
nonce: ${nonce}
data:
<---vvvvvvvvvvvvvv--->
${data}
<---^^^^^^^^^^^^^^--->
===> hash: ${hash}
============================
valid nonce : ${newNonce_}
===> hash: ${newHash_}
runtime: ${runtime_} ms
`
// 寫入 logs
fs.appendFileSync('./logs/log.txt', log, "utf8")
}