-
Notifications
You must be signed in to change notification settings - Fork 0
/
simpleChain.js
191 lines (176 loc) · 6.09 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
/*=========================================
|Configure your application to use levelDB|
|to persist blockchain dataset |
|=========================================*/
const level = require('level');
const chainDB = './chaindata';
const db = level(chainDB);
/*===== SHA256 with Crypto-js ===============================
| Learn more: Crypto-js: https://github.com/brix/crypto-js |
|==========================================================*/
const SHA256 = require('crypto-js/sha256');
/* ===== 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() {
/*============================================|
|Genesis block persists as the first block in |
|the blockchain using LevelDB with height=0. |
|============================================*/
this.getBlockHeight().then((blockHeight) => {
if (blockHeight == -1) {
this.addBlock(new Block("First block in the chain - Genesis block"));
}
});
}
/*============================================|
|addBlock(newBlock) function includes a method|
|to store newBlock with LevelDB. |
|============================================*/
// Add new block
async addBlock(newBlock){
const height = parseInt(await this.getBlockHeight());
newBlock.height = height + 1;
// UTC timestamp
newBlock.time = new Date().getTime().toString().slice(0,-3);
// previous block hash
if(newBlock.height > 0){
const previousBlock = await this.getBlock(height);
newBlock.previousBlockHash = previousBlock.hash;
}
// 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.saveBlockToLevelDB(newBlock.height, JSON.stringify(newBlock));
}
/*===================================================|
|Modify getBlock(height) function to retrieve a block|
|by its block height within the LevelDB chain | |
|===================================================*/
async getBlockHeight(){
return await this.getBlockHeightFromLevelDB() - 1;
}
/*===================================================|
|Modify getBlockHeight() function to retrieve current|
|block height within the LevelDB chain. |
|===================================================*/
// get block
async getBlock(blockHeight){
return JSON.parse(await this.getBlockFromLevelDB(blockHeight));
}
/*======================================|
|Modify the validateBlock() function to |
|validate a block stored within levelDB |
|======================================*/
// validate block
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;
}
}
/*==============================================|
|Modify the validateChain() function to validate|
|blockchain stored within levelDB |
|==============================================*/
// Validate blockchain
async validateChain(){
let errorLog = [];
const blockHeight = await this.getBlockHeightFromLevelDB();
for (let i = 0; i < blockHeight; i++) {
this.validateBlock(i).then(isValid => {
if (!isValid) {
errorLog.push(i)
}
if (i == blockHeight -1) {
if (errorLog.length > 0) {
console.log('Number of block errors = ' + errorLog.length);
console.log('Blocks with errors: ' + errorLog);
} else {
console.log('Blockchain valid');
}
}
});
}
}
/* ===== level db methods =====================================
| Methods responsible for persisting data |
| Learn more: level: https://github.com/Level/level |
| ==========================================================*/
// Data Layer
// Use LevelDB to persist blockchain
saveBlockToLevelDB(key, value) {
return new Promise((resolve, reject) => {
db.put(key, value, function(err) {
if (err) {
console.log('Block ' + key + ' save to levelDB failed', err);
reject();
} else {
resolve();
}
})
})
}
getBlockFromLevelDB(key) {
return new Promise((resolve, reject) => {
db.get(key, function (err, value) {
if (err) {
console.log('Unable to find Block ' + key + ' in levelDB', err);
reject(err);
} else {
resolve(value);
}
})
})
}
getBlockHeightFromLevelDB() {
return new Promise((resolve, reject) => {
let i = 0; //trigger genesis block file empty;
db.createReadStream().on('data', (data) => {
i++
}).on('error', (err) => {
console.log('failed to read', err)
resolve(err);
}).on('close', () => {
resolve(i)
})
})
}
} //Blochchain
/* ===== Testing ==============================================================|
| |
| Test adding and retrieval of blocks from peristent store |
| |
| ===========================================================================*/
let blockchain = new Blockchain();
(function theLoop (i) {
setTimeout(function () {
blockchain.addBlock(new Block('Block ' + i + ' added to levelDB')).then(() => {
if (--i) theLoop(i);
})
}, 100);
})(10);