-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimpleChain.js
226 lines (202 loc) · 6.34 KB
/
simpleChain.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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/* ===== SHA256 with Crypto-js ===============================
| Learn more: Crypto-js: https://github.com/brix/crypto-js |
| =========================================================*/
const SHA256 = require("crypto-js/sha256");
/* ===== LevelBD Javascript ===============================
| Learn more: Level: https://github.com/Level/level |
| =========================================================*/
const level = require("level");
const chainDB = "./blockchaindata";
const db = level(chainDB);
/* ===== Block Class ==============================
| Class with a constructor for block |
| ===============================================*/
class Block {
constructor(data) {
(this.hash = ""),
(this.height = 0),
(this.body = data),
(this.time = 0),
(this.previousBlockHash = "");
}
}
/* ===== Blockchain Class ==========================
| Class with a constructor for new blockchain |
| ================================================*/
class Blockchain {
/**
* Constructor for the Blockchain class. The constructor checks blockheight from DB
*/
constructor() {
this.getBlockHeight()
.then(result => {
// Checks blockheight
if (result === -1) {
console.log("There are no blocks in the blockchain. Adding Genesis");
this.addBlock(new Block("First block in the chain - Genesis block"))
.then(result =>
console.log("Genesis block was added to the blockchain")
)
.catch(err => console.log(err));
}
})
.catch(err =>
console.log("There was an error in the Blockchain construction!", err)
);
}
/**
* Function that fills in the necessary fields for the new block:
* hash, height, timestamp and finally adds it the DB
* @param {object} newBlock
*/
async addBlock(newBlock) {
let blockHeight = await this.getBlockHeight();
newBlock.height = blockHeight + 1;
// UTC timestamp
newBlock.time = new Date().getTime().toString();
if (newBlock.height > 0) {
const lastBlock = await this.getBlock(blockHeight);
newBlock.previousBlockHash = lastBlock.hash;
}
// Block hash with SHA256 using newBlock and converting to a string
newBlock.hash = SHA256(JSON.stringify(newBlock)).toString();
console.log("BLOCK TO ADD: ", JSON.stringify(newBlock));
// Adding block object to chain
this.addBlockToDB(newBlock.height, JSON.stringify(newBlock))
.then(() => {
return this.getBlockFromDB(newBlock.height);
})
.then(value => {
console.log("GOT: ", value);
})
.catch(function(err) {
console.error(err);
});
}
/**
* Function that returns the block height
* @return {number} the block height
*/
async getBlockHeight() {
return await this.getBlockHeightFromDB();
}
/**
*
* @param {number} blockHeight
* @return {Block} block for the given height
*/
async getBlock(blockHeight) {
return JSON.parse(await this.getBlockFromDB(blockHeight));
}
/**
* Function that validates the provided block
* @param {number} blockHeight of the corresponding block in the DB
* @return {boolean} true if block valid, false otherwise
*/
async validateBlock(blockHeight) {
// get block object
let block = await this.getBlock(blockHeight);
// get block hash
let blockHash = block.hash;
// remove block hash to test block integrity
block.hash = "";
// generate block hash
let validBlockHash = SHA256(JSON.stringify(block)).toString();
// Compare
if (blockHash === validBlockHash) {
return true;
} else {
console.log(
"Block #" +
blockHeight +
" invalid hash:\n" +
blockHash +
"<>" +
validBlockHash
);
return false;
}
}
/**
* Function that validates the whole exisint blockchain in the DB
* @return {boolean} true if valid
*/
async validateChain() {
let errorLog = [];
const blockHeight = await this.getBlockHeight();
for (var i = 0; i < blockHeight; i++) {
// validate block
if (!(await this.validateBlock(i))) errorLog.push(i);
// compare blocks hash link
let currentBlockHash = (await this.getBlock(i)).hash;
let nextBlockPreviousBlockHash = (await this.getBlock(i + 1))
.previousBlockHash;
if (currentBlockHash !== nextBlockPreviousBlockHash) {
errorLog.push(i);
}
}
if (errorLog.length > 0) {
console.log("Block errors = " + errorLog.length);
console.log("Blocks: " + errorLog);
} else {
console.log("No errors detected");
}
}
/**
* Function that adds a new block to the DB
* @param {int} key - the height of the block
* @param {object} value the block
* @return {Promise} as per the documentation of levelDB, w/o callback db.get returns a promise
*/
addBlockToDB(key, value) {
return db.put(key, value);
}
/**
*
* @param {number} key the height of the block
* @return {Promise} as per the documentation of levelDB, w/o callback db.get returns a promise
*/
getBlockFromDB(key) {
return db.get(key);
}
/**
* @return {Promise}
*/
getBlockHeightFromDB() {
return new Promise((resolve, reject) => {
let height = -1;
db.createReadStream()
.on("data", function(data) {
height++;
//console.log(data.key, "=", data.value);
})
.on("error", function(err) {
console.log("There was an error: ", err);
reject(err);
})
.on("close", function() {
console.log("Stream closed");
})
.on("end", function() {
console.log("Stream ended");
resolve(height);
});
});
}
}
blockchain = new Blockchain();
(function theLoop(i) {
setTimeout(async () => {
await blockchain.addBlock(new Block(`Testing data ${i}`));
if (--i) theLoop(i);
}, 100);
})(10);
// (async () => {
// await blockchain.addBlock(new Block("Second Block"));
// await blockchain.addBlock(new Block("Third Block"));
// await blockchain.addBlock(new Block("Fourth Block"));
// await blockchain.addBlock(new Block("Fifth Block"));
// await blockchain.addBlock(new Block("Sixth Block"));
// await blockchain.addBlock(new Block("Seventh Block"));
// })();
setTimeout(() => blockchain.validateChain(), 3000);