File tree Expand file tree Collapse file tree 1 file changed +30
-2
lines changed Expand file tree Collapse file tree 1 file changed +30
-2
lines changed Original file line number Diff line number Diff line change 1
- import { hash } from "./helpers" ;
1
+ import { hash , isValidHash , isValidHash } from "./helpers" ;
2
2
import { Block , Payload } from "./types" ;
3
3
4
4
export class Blockchain {
5
5
#chain: Block [ ] = [ ]
6
6
#difficulty: number
7
- #prefixPow = '0'
7
+ #prefixProofOfWork = '0'
8
8
9
9
constructor ( difficulty = 4 ) {
10
10
this . #difficulty = difficulty
@@ -45,4 +45,32 @@ export class Blockchain {
45
45
timestamp : + new Date ( )
46
46
}
47
47
}
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
+ }
48
76
}
You can’t perform that action at this time.
0 commit comments