-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathblockchain.js
62 lines (56 loc) · 2.11 KB
/
blockchain.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Get the sha256 hash function.
const crypto = require("crypto"), SHA256 = message => crypto.createHash("sha256").update(message).digest("hex");
class Block {
constructor(timestamp = "", data = []) {
this.timestamp = timestamp;
this.data = data;
this.hash = this.getHash();
this.prevHash = ""; // previous block's hash
this.nonce = 0;
}
// Our hash function.
getHash() {
return SHA256(this.prevHash + this.timestamp + JSON.stringify(this.data) + this.nonce);
}
mine(difficulty) {
// Basically, it loops until our hash starts with
// the string 0...000 with length of <difficulty>.
while (!this.hash.startsWith(Array(difficulty + 1).join("0"))) {
// We increases our nonce so that we can get a whole different hash.
this.nonce++;
// Update our new hash with the new nonce value.
this.hash = this.getHash();
}
}
}
class Blockchain {
constructor() {
// Create our genesis block
this.chain = [new Block(Date.now().toString())];
this.difficulty = 1;
this.blockTime = 30000;
}
getLastBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(block) {
block.prevHash = this.getLastBlock().hash;
block.hash = block.getHash();
block.mine(this.difficulty);
this.chain.push(Object.freeze(block));
this.difficulty += Date.now() - parseInt(this.getLastBlock().timestamp) < this.blockTime ? 1 : -1;
}
isValid(blockchain = this) {
// Iterate over the chain, we need to set i to 1 because there are nothing before the genesis block, so we start at the second block.
for (let i = 1; i < blockchain.chain.length; i++) {
const currentBlock = blockchain.chain[i];
const prevBlock = blockchain.chain[i-1];
// Check validation
if (currentBlock.hash !== currentBlock.getHash() || prevBlock.hash !== currentBlock.prevHash) {
return false;
}
}
return true;
}
}
module.exports = { Block, Blockchain };