-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockchain.js
More file actions
221 lines (187 loc) · 6.61 KB
/
Blockchain.js
File metadata and controls
221 lines (187 loc) · 6.61 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
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
/* ===== SHA256 with Crypto-js ===============================
| Learn more: Crypto-js: https://github.com/brix/crypto-js |
| =========================================================*/
const SHA256 = require('crypto-js/sha256');
const level = require('level');
const chainDB = './chaindata';
const db = level(chainDB);
const Block = require('./Block.js');
const hex2ascii = require('hex2ascii');
/* ===== Blockchain Class ==========================
| Class with a constructor for new blockchain |
| ================================================*/
class Blockchain{
constructor(){
this.getLastBlockHeight().then( (lastBlockHeight) => {
if (lastBlockHeight == -1) this.addBlock(new Block("Create First Block"));
});
}
// Add new block
async addBlock(newBlock){
try {
// Getting the height of the last block=
const lastBlockHeight = await this.getLastBlockHeight();
if (lastBlockHeight >= 0) {
newBlock.height = lastBlockHeight + 1;
// previous block
const previousBlock = await this.getBlockByHeight(lastBlockHeight);
// hash linking
newBlock.previousBlockHash = previousBlock.hash;
// encoding star's story
newBlock.body.star.story = Buffer(newBlock.body.star.story).toString('hex');
// Block hash with SHA256 using newBlock and converting to a string
newBlock.hash = SHA256(JSON.stringify(newBlock)).toString();
// Adding block object to chain
await this.saveBlock(newBlock.height, JSON.stringify(newBlock).toString());
} else if (lastBlockHeight == -1) {
// create and save Genesis block
newBlock.body = {"address": "0000GEN", "star": {"story": "First block in the chain - Genesis block"}};
// encoding star's story
newBlock.body.star.story = Buffer(newBlock.body.star.story).toString('hex');
newBlock.hash = SHA256(JSON.stringify(newBlock)).toString();
await this.saveBlock(newBlock.height, JSON.stringify(newBlock).toString());
}
console.log("Saved block successfully");
return newBlock.height
} catch (err) {
console.log("There was an error in the addBlock method of the Blockchain Class", err);
return err;
}
}
// Add data to levelDB with key/value pair
saveBlock(key,value){
return new Promise((resolve, reject) => {
// console.log('Block #' + key + ': ' + value );
db.put(key, value, function(err, result) {
if (err) reject(err);
else resolve(true);
});
});
}
// Get last block height i.e. chain length
getLastBlockHeight(){
return new Promise(function (resolve, reject){
let count = -1;
db.createReadStream()
.on('data', () => { count++; })
.on('error', (err) => {
reject(err);
console.log('Error counting block to get the lastBlockHeight', err);
})
.on('close', () => resolve(count) )
})
}
// get block
getBlockByHeight(blockHeight){
return new Promise((resolve, reject) => {
db.get(blockHeight, function(err, block) {
if (err) reject(err); // return console.log('Error getting block', err);;
else {
block = JSON.parse(block);
// decoding star's story
block.body.star.storyDecoded = hex2ascii(block.body.star.story);
resolve(block)
};
});
});
}
// Get block by hash
getBlockByHash(hash) {
return new Promise((resolve, reject) => {
let block = null;
db.createReadStream()
.on('data', (data) => {
if (JSON.parse(data.value).hash === hash) {
block = JSON.parse(data.value);
// decoding star's story
block.body.star.storyDecoded = hex2ascii(block.body.star.story);
}
})
.on('error', function (err) {
reject(err)
})
.on('close', function () {
resolve(block);
});
});
}
// Get block by WalletAddress
getBlockByWalletAddress(address) {
return new Promise((resolve, reject) => {
let blocks = [];
db.createReadStream()
.on('data', (data) => {
if (JSON.parse(data.value).body.address === address) {
let block = JSON.parse(data.value);
// decoding star's story
block.body.star.storyDecoded = hex2ascii(block.body.star.story);
blocks.push(block);
}
})
.on('error', function (err) {
reject(err)
})
.on('close', function () {
resolve(blocks);
});
});
}
// validate block
validateBlock(blockHeight){
return new Promise((resolve, reject) => {
// get block object
this.getBlockByHeight(blockHeight)
.then((block) => {
// get block hash
let blockHash = block.hash;
// console.log(blockHash);
// remove block hash to test block integrity
block.hash = '';
// generate block hash
let validBlockHash = SHA256(JSON.stringify(block)).toString();
// Compare
if (blockHash===validBlockHash) {
// console.log('Valid Block!')
resolve(true);
} else {
console.log('Block #'+blockHeight+' invalid hash:\n'+blockHash+'<>'+validBlockHash);
resolve(false);
}
}).catch( (err) => console.log("There was an error validatinBlock", err));
});
}
// Validate blockchain
async validateChain(){
let errorLog = [];
let blocks = [];
let ValidBlockArray = [];
const lastBlockHeight = await this.getLastBlockHeight();
for (let i = 0; i <= lastBlockHeight; i++) {
ValidBlockArray.push(this.validateBlock(i));
blocks.push(this.getBlockByHeight(i));
}
// verify each block is valid
Promise.all(ValidBlockArray).then((res) => console.log('all blocks valid ', res))
.catch((err) => console.log('invalid block in chain', err))
// compare blocks hash link
Promise.all(blocks).then((BlocksList) => {
if (BlocksList.length > 1) {
for (let b = 0; b < BlocksList.length -1; b++) {
let blockHash = BlocksList[b].hash;
let previousBlockHash = BlocksList[b+1].previousBlockHash;
if (blockHash !== previousBlockHash) {
errorLog.push('Error linking blockchain at block position #', b);
}
}
}
})
.catch((err) => console.log('invalid linkage in chain', err))
if (errorLog.length > 0) {
console.log('Block errors = ' + errorLog.length);
console.log('Blocks: '+errorLog);
} else {
console.log('No errors detected');
}
}
}
module.exports = Blockchain;