Skip to content

Commit 4f1b7a5

Browse files
feat: write mineBlock method
1 parent daa679f commit 4f1b7a5

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

src/blockchain.ts

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import { hash } from "./helpers";
1+
import { hash, isValidHash, isValidHash } from "./helpers";
22
import { Block, Payload } from "./types";
33

44
export class Blockchain {
55
#chain: Block[] = []
66
#difficulty: number
7-
#prefixPow = '0'
7+
#prefixProofOfWork = '0'
88

99
constructor(difficulty = 4) {
1010
this.#difficulty = difficulty
@@ -45,4 +45,32 @@ export class Blockchain {
4545
timestamp: +new Date()
4646
}
4747
}
48+
49+
mineBlock(block: Payload): Block {
50+
let nonce = 0
51+
let start = +new Date()
52+
53+
while(true) {
54+
const hashBlock = hash(JSON.stringify(block))
55+
const hashProofOfWork = hash(hashBlock + nonce)
56+
57+
if (isValidHash({ hash: hashProofOfWork, difficulty: this.#difficulty, prefix: this.#prefixProofOfWork })) {
58+
const finish = +new Date()
59+
const reducedHash = hashBlock.slice(0, 12)
60+
const timeMine = (finish - start) / 1000
61+
62+
console.log(`Block ${block.sequency} mined in ${timeMine} seconds. Hash ${reducedHash} (${nonce} tries)`)
63+
64+
return {
65+
header: {
66+
hash: hashBlock,
67+
nonce
68+
},
69+
payload: block
70+
}
71+
}
72+
73+
nonce += 1
74+
}
75+
}
4876
}

0 commit comments

Comments
 (0)