-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock.ts
52 lines (40 loc) · 1.15 KB
/
block.ts
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
import { SHA256 } from "crypto-js";
import { Transaction } from "./transaction";
export class Block {
private hash;
constructor (
private timestamp,
private transactions,
private previousHash = '',
private nonce = 0
) {
this.timestamp = Date.now();
this.hash = this.calculateHash();
}
//Implementing Proof-of-Work
mineBlock(difficulty: number) {
while(this.hash.substring(0, difficulty) !== Array(difficulty + 1).join("0")) {
this.nonce++;
this.hash = this.calculateHash();
}
console.log("Block mined: " + this.hash);
}
setHash(hash: string): void {
this.hash = hash;
}
getHash(): string {
return this.hash;
}
getTransactions(): Transaction[] {
return this.transactions;
}
setPreviousHash(hash: string): void {
this.previousHash = hash;
}
getPreviousHash(): string {
return this.previousHash;
}
calculateHash(): string {
return SHA256(this.previousHash + JSON.stringify(this.transactions).toString() + this.nonce).toString();
}
}