This repository has been archived by the owner on Jan 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
db.js
79 lines (70 loc) · 2.44 KB
/
db.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
const { Serialize } = require("enf-eosjs")
const types = Serialize.createInitialTypes();
const { open, asBinary } = require('lmdb');
const varuint32 = types.get("varuint32");
const uint32 = types.get("uint32");
const checksum256 = types.get("checksum256");
let rootDB,blocksDB, hashesDB, hashIndexDB, statusDB;
let dbPath = process.env.DB_PATH || 'lightproof-data'
const getDB = () => {
if(!rootDB) {
rootDB = open({ path: dbPath, compression: true });
blocksDB = rootDB.openDB({name:"blocksDB"});
hashesDB = rootDB.openDB({name:"hashesDB" });
hashIndexDB = rootDB.openDB({name:"hashIndexDB" });
statusDB = rootDB.openDB({name:"statusDB" });
}
return { rootDB, blocksDB, hashesDB, hashIndexDB, statusDB }
}
function deserialize(array){
const buffer = new Serialize.SerialBuffer({ TextEncoder, TextDecoder, array });
var id = Buffer.from(buffer.getUint8Array(32)).toString("hex");
var count = buffer.getVaruint32();
var nodes = [];
for (var i = 0 ; i < count; i++){
var index = buffer.getUint32();
var hashBuff = hashesDB.getBinary(index);
nodes.push(hashBuff.toString('hex'));
}
return {id, nodes} ;
}
function serialize(id, nodes){
var mappedNodes = map(nodes);
const buffer = new Serialize.SerialBuffer({ TextEncoder, TextDecoder });
checksum256.serialize(buffer, id);
varuint32.serialize(buffer, mappedNodes.length);
for (var node of mappedNodes) uint32.serialize(buffer, node);
return buffer.asUint8Array();
}
function map(nodes){
//TODO hashes count is last key of hashesDB + 1
var map = [];
for (var i = 0 ; i < nodes.length ;i++){
var buffNode = Buffer.from(nodes[i], "hex");
var index = hashIndexDB.get(buffNode);
if (!index) {
let hashesCount = 0;
for (let key of hashesDB.getKeys({ limit:1, reverse:1 })) hashesCount = key + 1;
hashIndexDB.putSync(buffNode, hashesCount);
hashesDB.putSync( hashesCount, asBinary(buffNode));
map.push(hashesCount);
// hashesCount++;
}
else map.push(index);
}
return map;
}
const getRange = async () =>{
let firstBlock, lastBlock;
for (let key of await blocksDB.getKeys({ limit:1 })) firstBlock = key;
for (let key of await blocksDB.getKeys({ limit:1, reverse:1})) lastBlock = key;
const lib = await statusDB.get("lib");
const lastBlockTimestamp = await statusDB.get("lastBlockTimestamp");
return {firstBlock, lastBlock, lib, lastBlockTimestamp}
}
module.exports = {
getDB,
getRange,
serialize,
deserialize
}