-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock.js
More file actions
38 lines (31 loc) · 1.08 KB
/
Copy pathblock.js
File metadata and controls
38 lines (31 loc) · 1.08 KB
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
const SHA256 = require('crypto-js/sha256');
class Block {
constructor(timestamp, transactions, previousHash = '') {
this.timestamp = timestamp;
this.transactions = transactions;
this.previousHash = previousHash;
this.hash = this.calculateHash();
this.nonce = 0;
}
calculateHash() {
return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.transactions) + this.nonce).toString();
}
mineBlock(difficulty) {
if(!this.hasValidTransactions) {
throw new Error('The block has invalid transactions');
}
while(this.hash.substring(0, difficulty) !== Array(difficulty + 1).join("0")) {
this.nonce++;
this.hash = this.calculateHash();
}
console.log("block mined", this.hash);
}
hasValidTransactions() {
if (this.transactions.length === 0) return true;
for(let transaction of this.transactions) {
if(!transaction.isValid()) return false;
}
return true;
}
}
module.exports = Block;