tovarish-relayer/lib/services/treeCache.js
2024-11-13 01:42:13 +00:00

66 lines
2.4 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 {
netId;
amount;
currency;
userDirectory;
PARTS_COUNT;
constructor({ netId, amount, currency, userDirectory, PARTS_COUNT = 4 }) {
this.netId = netId;
this.amount = amount;
this.currency = currency;
this.userDirectory = userDirectory;
this.PARTS_COUNT = PARTS_COUNT;
}
getInstanceName() {
return `deposits_${this.netId}_${this.currency}_${this.amount}`;
}
async createTree(events, tree) {
const bloom = new bloomfilter_js_1.default(events.length);
console.log(`Creating cached tree for ${this.getInstanceName()}\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 = `${this.getInstanceName()}_slice${index + 1}.json`;
await (0, data_1.saveUserFile)({
fileName,
userDirectory: this.userDirectory,
dataString,
});
}));
const dataString = bloom.serialize() + '\n';
const fileName = `${this.getInstanceName()}_bloom.json`;
await (0, data_1.saveUserFile)({
fileName,
userDirectory: this.userDirectory,
dataString,
});
}
}
exports.TreeCache = TreeCache;