-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock.js
More file actions
executable file
·27 lines (23 loc) · 767 Bytes
/
block.js
File metadata and controls
executable file
·27 lines (23 loc) · 767 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
const SHA256 = require("crypto-js/sha256");
class Block {
constructor (index, timestamp, data, previousHash = '') {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
// When creating a new Block, automatically calculate its hash.
this.hash = this.calculateHash();
this.nonce = 0;
}
calculateHash() {
return SHA256(this.index + this.previousHash + this.timestamp + 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);
}
}
module.exports = Block;