-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
105 lines (93 loc) · 3.07 KB
/
index.ts
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import * as CryptoJS from "crypto-js";
class Block {
static calculateBlockHash = (
index:number,
previousHash:string,
timestamp:number,
data:string
) : string =>
CryptoJS.SHA256(index + previousHash + timestamp + data).toString();
static validateStructure = (aBlock:Block): boolean =>
typeof aBlock.index === "number" &&
typeof aBlock.hash === "string" &&
typeof aBlock.previousHash === "string" &&
typeof aBlock.timestamp === "number" &&
typeof aBlock.data ==="string";
public index: number;
public hash: string;
public previousHash: string;
public data: string;
public timestamp: number;
constructor (
index: number,
hash: string,
previousHash: string,
data: string,
timestamp: number
) {
this.index = index;
this.hash = hash;
this.previousHash = previousHash;
this.data = data;
this.timestamp = timestamp;
}
}
const hashNumber = JSON.stringify(Math.random());
const genesisBlock:Block = new Block(0, hashNumber, "", "Hello", 1234567890);
let blockchain: [Block] = [genesisBlock];
const getBlockchain = ():Block[] => blockchain;
const getLatestBlock = ():Block => blockchain[blockchain.length - 1];
const getNewTimestamp = (): number => Math.round(new Date().getTime() / 1000)
const createNewBlock = (data:string):Block => {
const previousBlock:Block = getLatestBlock();
const newIndex:number = previousBlock.index + 1;
const newTimestamp:number = getNewTimestamp();
const newHash: string = Block.calculateBlockHash(
newIndex,
previousBlock.hash,
newTimestamp,
data
);
const newBlock:Block = new Block(
newIndex,
newHash,
previousBlock.hash,
data,
newTimestamp
);
addBlock(newBlock);
return newBlock;
};
const getHashforBlock = (aBlock:Block) :string =>
Block.calculateBlockHash(
aBlock.index,
aBlock.previousHash,
aBlock.timestamp,
aBlock.data
);
const isBlockValid = (
candidateBlock:Block,
previousBlock:Block
):boolean => {
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:Block):void => {
if(isBlockValid(candidateBlock, getLatestBlock())) {
blockchain.push(candidateBlock);
}
}
createNewBlock("second Block");
createNewBlock("third Block");
createNewBlock("fourth Block");
console.log(blockchain);
export {};