-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock.js
More file actions
28 lines (22 loc) · 801 Bytes
/
Copy pathblock.js
File metadata and controls
28 lines (22 loc) · 801 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
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();
}
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} was mined with ${this.hash}`);
}
calculateHash() {
return SHA256(JSON.stringify(this.data) + this.index + this.timestamp + this.previousHash + this.nonce).toString();
}
}
module.exports = Block;