-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock.js
More file actions
31 lines (22 loc) · 794 Bytes
/
block.js
File metadata and controls
31 lines (22 loc) · 794 Bytes
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
const { SHA256 } = require('crypto-js');
class Block {
constructor(data, index, timestamp = String(new Date()), previousHash) {
this.data = data;
this.index = index;
this.timestamp = timestamp;
this.previousHash = previousHash;
this.nonce = 0;
this.hash = this.calculateHash();
}
calculateHash() {
return SHA256(JSON.stringify(this.data) + this.index + this.timestamp + this.previousHash + 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 ${this.index + 1} mined: ${this.hash} `);
}
}
module.exports = Block;