tovarish-relayer/lib/services/treeCache.js

61 lines
2.3 KiB
JavaScript
Vendored

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TreeCache = void 0;
const bloomfilter_js_1 = __importDefault(require("bloomfilter.js"));
const data_1 = require("./data");
class TreeCache {
userDirectory;
PARTS_COUNT;
constructor({ userDirectory, PARTS_COUNT = 4 }) {
this.userDirectory = userDirectory;
this.PARTS_COUNT = PARTS_COUNT;
}
static getInstanceName({ netId, amount, currency, }) {
return `deposits_${netId}_${currency}_${amount}`;
}
async createTree({ netId, amount, currency, events, tree, }) {
const bloom = new bloomfilter_js_1.default(events.length);
const instance = TreeCache.getInstanceName({ netId, amount, currency });
console.log(`Creating cached tree for ${instance}\n`);
// events indexed by commitment
const eventsData = events.reduce((acc, { leafIndex, commitment, ...rest }, i) => {
if (leafIndex !== i) {
throw new Error(`leafIndex (${leafIndex}) !== i (${i})`);
}
acc[commitment] = { ...rest, leafIndex };
return acc;
}, {});
const slices = tree.getTreeSlices(this.PARTS_COUNT);
await Promise.all(slices.map(async (slice, index) => {
const metadata = slice.elements.reduce((acc, curr) => {
if (index < this.PARTS_COUNT - 1) {
bloom.add(curr);
}
acc.push(eventsData[curr]);
return acc;
}, []);
const dataString = JSON.stringify({
...slice,
metadata,
}, null, 2) + '\n';
const fileName = `${instance}_slice${index + 1}.json`;
await (0, data_1.saveUserFile)({
fileName,
userDirectory: this.userDirectory,
dataString,
});
}));
const dataString = bloom.serialize() + '\n';
const fileName = `${instance}_bloom.json`;
await (0, data_1.saveUserFile)({
fileName,
userDirectory: this.userDirectory,
dataString,
});
}
}
exports.TreeCache = TreeCache;