-
Notifications
You must be signed in to change notification settings - Fork 0
/
Block.js
42 lines (36 loc) · 887 Bytes
/
Block.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
import SHA256 from "crypto-js/sha256.js";
export default class Block {
constructor(transactions, timestamp, previousHash = "") {
this.transactions = transactions;
this.timestamp = timestamp;
this.previousHash = previousHash;
this.hash = this.calculateHash();
this.nonce = 0;
}
calculateHash() {
return SHA256(
this.index +
this.timestamp +
this.previousHash +
JSON.stringify(this.data) +
this.nonce
).toString();
}
mineBlock(difficulty) {
while (
this.hash.substring(0, difficulty) !== Array(difficulty + 1).join("0")
) {
this.nonce++;
this.hash = this.calculateHash();
}
console.log("Block mined:", this.hash);
}
hasValidTransactions() {
for (const tx of this.transactions) {
if (!tx.isValid()) {
return false;
}
}
return true;
}
}