-
Notifications
You must be signed in to change notification settings - Fork 0
/
miner.js
66 lines (57 loc) · 1.58 KB
/
miner.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
require('dotenv').config()
const fetch = require('node-fetch')
const shajs = require('sha.js')
// Helper functions
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function callEndpointAfterCD(endpoint, method, data) {
try {
let res = await fetch(
`https://lambda-treasure-hunt.herokuapp.com/api/${endpoint}/`,
{
method: `${method}`,
headers: { Authorization: `Token ${process.env.TOKEN}` },
body: JSON.stringify(data)
}
)
let status = res.status
let obj = await res.json()
let result = { ...obj, status }
await sleep(obj.cooldown * 1000)
console.log(result)
return result
} catch (err) {
console.error(err)
}
}
function validate_proof(last_proof, proof, difficulty) {
let hash = shajs('sha256')
.update(`${last_proof}${proof}`)
.digest('hex')
return hash.substring(0, difficulty) === '0'.repeat(difficulty)
}
// Miner
async function main() {
while (true) {
let last_block = await callEndpointAfterCD('bc/last_proof', 'get')
let last_proof = parseInt(last_block.proof)
let difficulty = last_block.difficulty
let proof = last_proof
let is_valid = false
console.log(`🔍 Validating proof`)
while (!is_valid) {
proof += 1
is_valid = validate_proof(last_proof, proof, difficulty)
}
console.log(`✅ Finished validating. Proof is ${proof}`)
let mine = await callEndpointAfterCD('bc/mine', 'post', {
proof
})
if (mine.status === 200) {
console.log(`💖 Mined successfully!`)
}
break
}
}
main()