-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
61 lines (61 loc) · 2.31 KB
/
index.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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const CryptoJS = require("crypto-js");
class Block {
constructor(index, hash, previousHash, data, timestamp) {
this.index = index;
this.hash = hash;
this.previousHash = previousHash;
this.data = data;
this.timestamp = timestamp;
}
}
Block.calculateBlockHash = (index, previousHash, timestamp, data) => CryptoJS.SHA256(index + previousHash + timestamp + data).toString();
Block.validateStructure = (aBlock) => typeof aBlock.index === "number" &&
typeof aBlock.hash === "string" &&
typeof aBlock.previousHash === "string" &&
typeof aBlock.timestamp === "number" &&
typeof aBlock.data === "string";
const hashNumber = JSON.stringify(Math.random());
const genesisBlock = new Block(0, hashNumber, "", "Hello", 1234567890);
let blockchain = [genesisBlock];
const getBlockchain = () => blockchain;
const getLatestBlock = () => blockchain[blockchain.length - 1];
const getNewTimestamp = () => Math.round(new Date().getTime() / 1000);
const createNewBlock = (data) => {
const previousBlock = getLatestBlock();
const newIndex = previousBlock.index + 1;
const newTimestamp = getNewTimestamp();
const newHash = Block.calculateBlockHash(newIndex, previousBlock.hash, newTimestamp, data);
const newBlock = new Block(newIndex, newHash, previousBlock.hash, data, newTimestamp);
addBlock(newBlock);
return newBlock;
};
const getHashforBlock = (aBlock) => Block.calculateBlockHash(aBlock.index, aBlock.previousHash, aBlock.timestamp, aBlock.data);
const isBlockValid = (candidateBlock, previousBlock) => {
if (Block.validateStructure(candidateBlock)) {
return false;
}
else if (previousBlock.index + 1 !== candidateBlock.index) {
return false;
}
else if (previousBlock.hash !== candidateBlock.previousHash) {
return false;
}
else if (getHashforBlock(candidateBlock) !== candidateBlock.hash) {
return false;
}
else {
return true;
}
};
const addBlock = (candidateBlock) => {
if (isBlockValid(candidateBlock, getLatestBlock())) {
blockchain.push(candidateBlock);
}
};
createNewBlock("second Block");
createNewBlock("third Block");
createNewBlock("fourth Block");
console.log(blockchain);
//# sourceMappingURL=index.js.map