-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
48 lines (38 loc) · 1010 Bytes
/
utils.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
'use strict';
const Crypto = require('crypto-js');
const calcHash = (index, previousHash, timestamp, data) => {
const blockString = `${index}|${previousHash}|${timestamp}|${data}`;
return Crypto.SHA256(blockString).toString() ;
};
const calcHashForBlock = (block) => {
const args = [block.index, block.previousHash, block.timeStamp, block.data];
return Reflect.apply(calcHash, null, args);
};
const getBlockAtIndex = (chain, index) => {
const hashList = Reflect.ownKeys(chain);
const hashAtIndex = hashList[index];
return chain[hashAtIndex];
};
const sortBlocks = (blocks) => {
const sortedBlocks = {};
const tmpArray = [];
Reflect
.ownKeys(blocks)
.forEach((hash) => {
const block = blocks[hash];
tmpArray[block.index] = hash;
});
tmpArray
.forEach((hash) => {
if (hash){
sortedBlocks[hash] = blocks[hash];
}
});
return sortedBlocks;
};
module.exports = {
calcHash,
calcHashForBlock,
getBlockAtIndex,
sortBlocks
};